Question

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!

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top