Issue
Given the following Code:
private static final Set<String> set =
new TreeSet<String>(String.CASE_INSENSITIVE_ORDER) {{
addAll(asList("string1", "string2"));
}};
How would one go about creating a set without Double Brace Initialization? I have Sonar complaining about it and can't figure out a solution due to my Set both needing values as it has to be final and having to ignore case sensitiveness.
Solution
You can use a static initializer:
private static final Set<String> set;
static {
set = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
set.addAll(asList("string1", "string2"));
}
Note that making it final
does not make the set itself immutable or unmodifiable. It's still possible to add or remove elements after the set has been initialized.
If you want to make the set unmodifiable (to make sure its contents cannot be modified after it has been initialized), you can also wrap it with Collections.unmodifiableSet()
:
static {
Set<String> s = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
s.addAll(asList("string1", "string2"));
set = Collections.unmodifiableSet(s);
}
Answered By - Jesper
Answer Checked By - Timothy Miller (JavaFixing Admin)