문제

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!

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top