Initializing with Character vs char array
Asked Answered
M

2

10

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!

Monsignor answered 9/4, 2013 at 17:54 Comment(3)
Because char[] is considered as a single parameter in the T ... params, while Character[] parameter is considered the array parameter for T ... params.Contagious
@LuiggiMendoza: that should be an answer.Ferrick
Also, you don't need to declare the type while initialising as "Arrays.asList('a','e','i','o','u','A','E','I','O','U');" should also work and also eradicates the confusion, provided you have mentioned the type while declaring the list.Wolfish
K
10

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
Kryska answered 9/4, 2013 at 17:55 Comment(0)
R
1

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.

Rationalize answered 9/4, 2013 at 17:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.