当前位置:网站首页>guava:创建immutableXxx对象的3种方式

guava:创建immutableXxx对象的3种方式

2022-07-06 13:10:00 amadeus_liu2

可以通过of copyOf 和builder 三种方式创建不可变对象

package com.example.app;

import com.google.common.collect.ImmutableSet;

import java.util.HashSet;
import java.util.Set;

public class ImmutableTest2 {
    public static void main(String[] args) {
        Set<String> originalSet=new HashSet<>();
        originalSet.add("abc");
        originalSet.add("def");
        originalSet.add("ghi");

        ImmutableSet<String> immutableSet = ImmutableSet.copyOf(originalSet);
        for(String str: immutableSet){
            System.out.println(str);
        }

        System.out.println("______________________________________________________");

        ImmutableSet<String> immutableSet1 = ImmutableSet.of("abc","def","ghi");
        for(String str: immutableSet1){
            System.out.println(str);
        }
        System.out.println("______________________________________________________");

        ImmutableSet<String> immutableSet2 = ImmutableSet.<String>builder()
                .add("abc")
                .add("def")
                .add("ghi")
                .build();

        for(String str: immutableSet2){
            System.out.println(str);
        }

    }
}

原网站

版权声明
本文为[amadeus_liu2]所创,转载请带上原文链接,感谢
https://blog.csdn.net/amadeus_liu2/article/details/125613401