Initialization with Character vs char array

Prints false

List vowelsList=Arrays.asList(new char[]{'a','e','i','o','u'});
System.out.println(vowelsList.contains('a'));//false

Prints true

List vowelsList=Arrays.asList(new Character[]{'a','e','i','o','u'});
System.out.println(vowelsList.contains('a'));//true

charautoboxing to Characterwhich I used in char array initializer. Why am I getting different results!

+5
source share
2 answers

Also print

vowelsList.size();

for both, and you will see the difference;)

Spoiler:

The general type of the first method is char[], so you get a list of size one. His type List<char[]>. The general type of the second code Character, so your list will have as many entries as an array. Type List<Character>.


To avoid this error, do not use raw types! The following code will not compile :

List<Character> vowelsList = Arrays.asList(new char[]{'a','e','i','o','u'});

The following three lines are in order:

List<char[]> list1 = Arrays.asList(new char[]{'a','e','i','o','u'}); // size 1
List<Character> list2 = Arrays.asList(new Character[]{'a','e','i','o','u'}); // size 5
List<Character> list3 = Arrays.asList('a','e','i','o','u'); // size 5
+6

@jlordo (+1) , , . char[], char element a. 5 Character 'a', 'e', ​​'i', 'o', 'u', true.

+1

All Articles