This question already has answers here:
How to initialize HashSet values by construction?
                            
                                (23个答案)
                            
                    
                去年关闭。
        

    

我想创建不区分大小写的Fruits最终TreeSet值。
有什么办法,我可以更改fruits1变量声明中的某些内容,以便获得所需的结果并避免使用方法addFruits()

import java.util.Arrays;
import java.util.SortedSet;
import java.util.TreeSet;

public class Fruits {

public static SortedSet<String> fruits = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);


//public static final SortedSet<String> fruits1 = new TreeSet<>(Arrays.asList("Apple", "Banana", "Orange", "Pineapple", "banana"));

public void addFruits(){
    fruits.add("Apple");
    fruits.add("Banana");
    fruits.add("Orange");
    fruits.add("PineApple");
    fruits.add("banana");
}}

最佳答案

您可以使用双括号初始化或静态块,但是您的解决方案不会阻止您使用final:

//double brace initialization
private static final Set<String> FRUITS = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER) {{
    this.add("Apple");
    this.add("Banana");
    this.add("Orange");
    this.add("PineApple");
    this.add("banana");
}};

//Or a static block
static {
    FRUITS.add("Apple");
    FRUITS.add("Banana");
    FRUITS.add("Orange");
    FRUITS.add("PineApple");
    FRUITS.add("banana");
}


另外考虑将双括号初始化包装在Collections#unmodifiableSet中,以防止其被修改

09-05 00:47