10

I'm looking to convert an array of char to a Set of Characters.

Logically if I wrote out something like How to convert an Array to a Set in Java instead of using the built in functions it would work. However using built in functions with generics it does not.

    TreeSet<Character> characterSet = Sets.newTreeSet();

    String myString = "string";
    Character [] characterArray = {'s','t','r','i','n','g'};


    Collections.addAll(characterSet,characterArray); // This works
    Collections.addAll(characterSet,myString.toCharArray()); // This Does not

Why doesn't it cast array of char to characters?

As a follow up to an answer. (Thank you btw) I think a simple example of what I mean is why does the first line implicitly cast but the second line does not?

    Character [] characterArray  = {'s','t','r','i','n','g'}; // works
    Character [] characterArray2 = myString.toCharArray(); // does not work

My understanding is both of the right hand sides make character[] variabless

Community
  • 1
  • 1
Carlos Bribiescas
  • 4,197
  • 9
  • 35
  • 66

1 Answers1

12

Because myString.toCharArray() will return char[] which is not Character[]. You can verify it by this simple test:

char[] a = { 'a' };
Character[] b = { 'b' };
a = b; //doesn't work, because char[] is not a Character[]

The Character[] characterArray = {'s','t','r','i','n','g'}; however is compliant with Collections.addAll(...), because when the array is initialized, each of the values is autoboxed from char to Character.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147