[英]Why doesn't implicit casting happen here?
I'm looking to convert an array of char
to a Set
of Characters. 我正在寻找将
char
数组转换为一Set
字符。
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. 从逻辑上讲,如果我写出如何将数组转换为Java中的Set而不是使用内置函数,它将起作用。 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
? 为什么不将
char
数组转换为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 我的理解是右手边的两个
character[]
变量
Because myString.toCharArray()
will return char[]
which is not Character[]
. 因为
myString.toCharArray()
将返回不是Character[]
char[]
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'};
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
. 但是与
Collections.addAll(...)
兼容,因为在初始化数组时,每个值都会从char
自动装箱到Character
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.