Why changes in sublist are reflected in the original list?

前端 未结 4 711
余生分开走
余生分开走 2020-12-11 17:11

I know that Collections in Java are mutable when you pass them through references.
I want to know exactly what happens in memory addresses of original-list

4条回答
  •  难免孤独
    2020-12-11 17:49

    Check this link.

    SubList returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.

    So your list2 is just a sub-view of your orginal list.That is why, when you are clearing list2, you are losing corresponding values in orginal list.Check this code.

    public static void main(String[] args)
        {   
            List list = new ArrayList();
            list.add("1");
            list.add("2");
            list.add(1, "3");
            List list2 = new LinkedList(list);
            list.addAll(list2);
            System.out.println(list);
            list2 = list.subList(2, 5);
            System.out.println(list2);
            list2.clear();               //Changes are made to list1
            System.out.println(list);
    
        }
    

    O/P

    [1, 3, 2, 1, 3, 2]
    [2, 1, 3]
    [1, 3, 2]
    

提交回复
热议问题