Below code actually modifies original list x
. Is there anyway to sub list the main list considering that modification to sub list should not modify the original list?
List<Integer> x = new ArrayList<Integer>();
x.add(1);
x.add(2);
x.add(3);
x.add(4);
x.add(5);
List<Integer> y = new ArrayList<Integer>();
y.add(1);
y.add(2);
y.add(3);
final List<Integer> z = x.subList(0, 4);
System.out.println("sublist " + z.toString());
z.removeAll(y);
System.out.println("Main list after removing sublist " + x.toString());
Result:
sublist [1, 2, 3, 4]
Main list after removing sublist [4, 5]
Again, It will return the list between the specified index fromIndex(inclusive) and toIndex(exclusive). Remember that we said the list returned by the subList() method is only a view that has a reference to the original list. If you do any changes to the sublist, it will affect the original list as well.
Create a List by passing another list as a constructor argument. List<String> copyOflist = new ArrayList<>(list); Create a List and use addAll method to add all the elements of the source list.
List interface method subList() can be used to get a sublist of the list. It requires start and end index. This sublist contains the same objects as in original list and changes to sublist will also reflect in original list.
Try to use List<Integer> z = new ArrayList<>(x.subList(0, 4))
List<Integer> x = new ArrayList<Integer>();
x.add(1);
x.add(2);
x.add(3);
x.add(4);
x.add(5);
List<Integer> y = new ArrayList<Integer>();
y.add(1);
y.add(2);
y.add(3);
final List<Integer> z = new ArrayList<>(x.subList(0, 4));
System.out.println("sublist " + z.toString());
z.removeAll(y);
System.out.println("Main list after removing sublist " + x.toString());
Output:
sublist [1, 2, 3, 4]
Main list after removing sublist [1, 2, 3, 4, 5]
If you do not want the sublist to be a "window" into the original, you need to make a copy, like this:
final List<Integer> z = new ArrayList<Integer>(x.subList(0, 4));
If you would rather have an unmodifiable list without making a copy, you could use Collections.unmodifiableList
:
final List<Integer> z = Collections.unmodifiableList(x.subList(0, 4));
z.removeAll(y); // <<== This will now fail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With