Reputation: 69259
I got a question about constructing a new ArrayList
based on an already existing list, I need it to reverse a List
. I do not need to deep clone the elements, since I only inspect their values and do not change them.
My old, working, code, it seems a bit hackish to me, so I think I had problems with it in the past:
Collections.sort(invoiceWordGroups, new WordGroup.WordGroupComparator());
insertAttributes(topAttributeWords, invoiceWordGroups, templateId, templateAttributeManager, invoiceMarginDataVAT);
Collections.reverse(invoiceWordGroups);
insertAttributes(bottomAttributeWords, invoiceWordGroups, templateId, templateAttributeManager, invoiceMarginDataVAT);
My new code, I will test it aswell ofcourse, but even then some errors might remain to be in there, if my basic concepts are not oK. So would this have the same behaviour?
Collections.sort(invoiceWordGroups, new WordGroup.WordGroupComparator());
List<WordGroup> invoiceWordGroupsReverse = new ArrayList<>(invoiceWordGroups);
Collections.reverse(invoiceWordGroupsReverse);
insertAttributes(topAttributeWords, invoiceWordGroups, templateId, templateAttributeManager, invoiceMarginDataVAT);
insertAttributes(bottomAttributeWords, invoiceWordGroupsReverse, templateId, templateAttributeManager, invoiceMarginDataVAT);
The question is about invoiceWordGroups
, which is of type List<WordGroup>
. The reason I am changing it is because I will need to use the lists multiple times now, and constantly reversing it does definately not seem to be a good option.
Upvotes: 0
Views: 118
Reputation: 15141
If you check the Java source code the copy constructor for ArrayList creates a new list object which copies (hence the name copy constructor) the internal array (but even though it's a copy of the original array it still points to the same elements!!!). This internal array object is not shared therefore and it is the object which is responsible for what a given list object actually stores and in what order:
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}
So reversing one list won't affect the order of the other. Same goes for adding/deleting elements from one list or the other.
You said that those are read-only objects then it will be ok but remember that even though both lists are different objects they still point to the same elements, so changing the state of object X in list1 will also be shown when accessing that object X with list2.
Upvotes: 3