is it somehow possible to get a sorted List
view of a List
with the elements from the original List, modify the elements, for example set a property, but the original List should reflect the changes?
Background is I'm s开发者_Go百科orting two Lists, then for each equal element I'm setting a property (basically it's the intersection) but finally I need the unsorted List with the modified elements.
kind regards,
JohannesProbably the simplest thing to do is add the elements to a new list, sort that list, and when you modify the elements, the original elements will still be modified...
List<?> origA;
List<?> origB;
List<?> newA = new ArrayList<?>(origA);
List<?> newB = new ArrayList<?>(origB);
Collections.sort(newA);
Collections.sort(newB);
// do mods
If the List
holds references to objects (not primitive data types), then just copy the list, sort it and modify the elements.
Does it have to be a list? If you keep your elements in a TreeSet
, they will always be sorted as you iterate through them, even after you add/remove the elements. Remember though that modifying an element already in the TreeSet
may break the sort order. You can remove and add the element to the TreeSet
to get around that.
If you have to use a list, you can use Collections.sort(List list)
after adding or modifying an element. Of course, if you have to call it often, there will be a performance hit. If performance is a concern, you can just insert the new element (or move the modified one) to maintain the sorted order, which will be cheaper than sorting it: O(n) vs O(n*log(n))
精彩评论