1

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

4
  • 1
    Why are you copying the array on each iteration of the loop? Also, define 'not working'. Commented Mar 12, 2013 at 19:33
  • So you want a deep copy in other words? Commented Mar 12, 2013 at 19:33
  • 2
    possible duplicate of Deep copy of an object array Commented Mar 12, 2013 at 19:34
  • is a copy of my city... I am using for TSP problem Commented Mar 12, 2013 at 20:18

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

the array cities is a type of City (coordinate x, coordinate y, boolean visited) the problem is the boolean value is not changing... City[] tempCities = Arrays.copyOf(cities, cities.length); when i change the property of tempCities, its changing even the property of the city. es: tempCities[i].setVisited(); this change cities[i] as visited, which I do not want... I tried clone too...but no use, and I cant use close because it is slow

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.