通常不建议直接公开final static Set
,因为这可能导致意外的操作和未知效果。解决方法是通过公开一个不可变副本或使用方法来提供只读访问。以下是两个解决方案的示例代码:
public class MyClass {
private static final Set MY_SET = new HashSet<>();
public static Set getMySet() {
return Collections.unmodifiableSet(MY_SET);
}
}
public class MyClass {
private static final Set MY_SET = new HashSet<>();
public static final Set MY_SET_READONLY = Collections.unmodifiableSet(MY_SET);
}