Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sub list without modifying original list in java

Tags:

java

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]
like image 206
mahesh Avatar asked Nov 27 '13 16:11

mahesh


People also ask

Does subList change the original list?

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.

How do I add a list to an existing list in Java?

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.

How do I get a list of subs from a 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.


2 Answers

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]
like image 173
Masudul Avatar answered Oct 07 '22 10:10

Masudul


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.
like image 5
Sergey Kalinichenko Avatar answered Oct 07 '22 11:10

Sergey Kalinichenko