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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With