Hello, I am writing a database in Java and trying to sort by place.

private void sortByPlace() { ArrayList<String> tmpplace = place; Collections.sort(place); for (int i = 0; i < place.size(); i++) { name.set(i, name.get(tmpplace.indexOf(place.get(i)))); surname.set(i, surname.get(tmpplace.indexOf(place.get(i)))); } printDB(); menu(); } 

The algorithm is as follows:

1) I create a temporary list tmpplace and write place to it.

2) Sort place.

3) I change the name and surname so that they correspond to the changed place.

Why tmpplace.indexOf (place.get (i)) = i? Thank you in advance.

  • 2
    You do not create a temporary list, you simply copy the link to it. You have not given a list, it is still one. You can create a new one by calling new ArrayList<>(place); - etki

1 answer 1

By writing ArrayList tmpplace = place, you did not thereby write the object to a new object, but put a link to the object. Both of your variables refer to one object in memory, roughly sorted one - the other sorted. Therefore, it is not surprising that when you search for the first occurrence of the i-th element of the array from the same array, it returns you i.