0

I want to create case insensitive final TreeSet Values of Fruits. Is there any way, I can change something in the fruits1-variable declaration, so I can get the desired result and can avoid method 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");
}}
Optimight
  • 2,989
  • 6
  • 30
  • 48
  • `fruits1.addAll(Arrays.asList(...))`? – Jai Feb 25 '19 at 01:19
  • Why is this a duplicate? He might not be very clear, but he's trying to get a constructor that combines both `TreeSet(Collection)` and `TreeSet(Comparator)`. – Jai Feb 25 '19 at 01:25

1 Answers1

1

You can use double brace initialization or a static block, but your solution doesn't stop you from using 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");
}

Additionally consider wrapping the double brace initialization in Collections#unmodifiableSet to keep it from being modified

Rogue
  • 11,105
  • 5
  • 45
  • 71