Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't implicit casting happen here?

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

like image 216
Carlos Bribiescas Avatar asked Apr 22 '15 11:04

Carlos Bribiescas


1 Answers

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.

like image 187
Konstantin Yovkov Avatar answered Nov 16 '22 02:11

Konstantin Yovkov