Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing with Character vs char array

This prints false

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

This prints true

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

char is autoboxed to Character which I had used in char array initailizer..Why am I getting different results!

like image 533
Anirudha Avatar asked Apr 09 '13 17:04

Anirudha


2 Answers

Also print

vowelsList.size();

for both, and you'll see the difference ;)

Spoiler:

The generic type of the first method is char[], so you'll get a list of size one. It's type is List<char[]>. The generic type of your second code is Character, so your list will have as many entries as the array. The type is List<Character>.


To avoid this kind of mistake, don't use raw types! Following code will not compile:

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

Following three lines are fine:

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
like image 69
jlordo Avatar answered Nov 10 '22 10:11

jlordo


As @jlordo (+1) said your mistake is in understanding what does your list contain. In first case it contains one element of type char[], so that it does not contain char element a. In second case it contains 5 Character elements 'a','e','i','o','u', so the result is true.

like image 42
AlexR Avatar answered Nov 10 '22 11:11

AlexR