当前位置:网站首页>Guava: three ways to create immutablexxx objects

Guava: three ways to create immutablexxx objects

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

Can pass of copyOf and builder There are three ways to create immutable objects

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://yzsam.com/2022/187/202207061310311684.html