Search code examples
javalistcollectionsinsertfinal

Java - how to insert into final list


I have a list of objects I need to operate on.

Depending on the object, the operation will result in new object that need be placed in order of creation JUST before the object that was operated on.

Under normal circumstances, I'd create a new list and then simply switch the lists. This is, however, not possible in this particular case because the list is final.

Is there a more elegant solution than to create a new list, overwrite the existing list and then add as many elements as are left when all existing elements of the old list are overwritten?

UPDATE: psuedocode

I am looking for something like this:

class Some{ //provided
    public final List<Thing> finalList = ...
}

class MyClass{
    void handle(Thing t, List<Thing> newThings){
        //do something to t
        //probably create and add new instances of Thing to newThings
    }

    void handle(Some s){
        for(Thing t : s.finalList){
            List<Thing> newThings = new ArrayList<>();
            handle(t,newThings);
            for(Thing nt : newThings){
                //insert nt into s.finalList s.th. it is immediately precedes t
            }
        }
    }

Solution

  • Use a ListIterator and its previous() method to insert before the current element. Don't forget to next() back to where you were initially.