Reputation: 5759
In Java, given a list xs
can we obtain the list ys
such that the nth element of ys
is given a new value. xs
is not modified. Can this be done without having to copy all of xs
, referring to the copy as ys
then modifying ys
?
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> xs = new ArrayList<Integer>(100);
xs.add(10);
System.out.println(xs.get(0)); // prints 10
destructiveCall(xs);
System.out.println(xs.get(0)); // prints 5
List<Integer> ys = nonDestructiveUpdate(xs);
System.out.println(xs.get(0)); // prints 5 (the value has not changed)
System.out.println(ys.get(0)); // prints 20 (the value set in the nonDestructiveUpdate)
}
private static void destructiveCall(List<Integer> xs) {
xs.set(0, 5);
}
private static List<Integer> nonDestructiveUpdate(List<Integer> xs) {
List<Integer> ys = new ArrayList<Integer>(xs);
// is there a way of doing this without copying the whole list?
ys.set(0, 20);
return ys;
}
}
Upvotes: 1
Views: 99
Reputation: 14964
It's not clear what you're trying to accomplish. If you want to update ys without updating xs, then they have separate states. If you're worried about the list elements being cloned, they won't be. But you probably do want the references to be copied, so that you can manipulate them non-destructively.
If you're looking for ys to keep track of only the changes, then @libik has a good suggestion, but it'll get tricky very quickly depending on what operations you need to support (if it's just updates, it won't be too hard, but inserts/deletes will be harder).
Upvotes: 0
Reputation: 23029
You can write your own class which holds "base list", in your case xs
and another virtual list - ys
, where you track the changes. You can create methods and iterator for your ys
virtual list, so it can appear as real list, even it is not.
But in standard libraries o Java funcionality I do not know about something like this.
Upvotes: 3