sub list without modifying original list in java

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.

Tags:

Java