当前位置:网站首页>guava:Collections. The collection created by unmodifiablexxx is not immutable

guava:Collections. The collection created by unmodifiablexxx is not immutable

2022-07-06 21:33:00 amadeus_ liu2

One 、 Example

package com.example.app;

import com.google.common.collect.ImmutableSet;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class ImmutableTest {
    public static void main(String[] args) {
        List<String> stringList=new LinkedList<>();
        stringList.add("abc");
        stringList.add("def");

        List<String> stringList1 = Collections.unmodifiableList(stringList);
        stringList.remove(0);
        System.out.println(stringList1);
    }
}

Run program output :
 Insert picture description here
Cannot pass Collections.unmodifiableXXX Create a reference to modify the object , But because of the original stringList It can be modified , and stringList1 and stringList Point to the same object ,stringList Modification will inevitably make stringList1 change .

原网站

版权声明
本文为[amadeus_ liu2]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061310311755.html