如何在Java中复制(内存)数组? [英] How to copy(memory) array in java?

查看:76
本文介绍了如何在Java中复制(内存)数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想复制一个数组...,但我不想使用复制速度较慢的克隆". 我尝试了arraycopy和copyOf,但无法正常工作

Hi I want to copy an array...and I do not want to use "clone" which is slow to copy.. I tried arraycopy and copyOf, but it is not working

for (int i = 0; i < arraySize; i++) {
            City[] tempCities = Arrays.copyOf(cities, cities.length) ;
            distance = 0;
            tempCities[i].setVisited();
}

但这会修改​​我的原始数组(城市).有谁知道如何复制并且没有另一个指向同一对象的指针

but this modify my original array(cities). Does anyone know how to copy and not have another pointer to the same object

推荐答案

真正的问题是您将引用存储在数组中.如果希望新数组中的对象独立于原始数组中的对象,则必须进行深层复制.为此,cities[i].clone()是您的朋友.

The real issue is that you store references in the array. If you want the objects in the new array to be independent of the objects in the original array, you have to make a deep copy. For that, cities[i].clone() is your friend.

关于您的性能问题,很可能是由于您在每次循环迭代期间复制了阵列.这非常浪费;一个副本就足够了.

As to your performance issue, it could well be due to the fact that you copy the array during every iteration of the loop. This is very wasteful; a single copy would suffice.

这篇关于如何在Java中复制(内存)数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆