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

Vannian
  • 1,490
  • 5
  • 14
  • 26

1 Answers1

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 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 – Vannian Mar 12 '13 at 20:15