int[] AllCards = {1,2,3,4,5,6,7,8,9,10};
if(Arrays.asList(AllCards).contains(1))
System.out.println("yes");
else {
System.out.println("no");
}
I have this code and it just keeps printing no
instead of yes
. What is wrong?
int[] AllCards = {1,2,3,4,5,6,7,8,9,10};
if(Arrays.asList(AllCards).contains(1))
System.out.println("yes");
else {
System.out.println("no");
}
I have this code and it just keeps printing no
instead of yes
. What is wrong?
Integer[] AllCards = {1,2,3,4,5,6,7,8,9,10};
if(Arrays.asList(AllCards).contains(1))
System.out.println("yes");
else {
System.out.println("no");
}
to understand why check this : https://stackoverflow.com/a/1467940/4088809
Since AllCards
is an int
array the call Arrays.asList(AllCards)
returns a List with a single element, namely AllCards
.
If you don't want to change AllCards
to an Integer
array you can write the following to test if it contains 1:
boolean containsOne = Arrays.stream(AllCards).anyMatch(n -> n == 1);
Problem is that 1
is autoboxed as an Integer
not an int
.
Change declaration to Integer[]
Change int
to Integer
:
Integer[] AllCards = {1,2,3,4,5,6,7,8,9,10};
if(Arrays.asList(AllCards).contains(1))
System.out.println("yes");
else {
System.out.println("no");
}
In Java, the 'int' type is a primitive , whereas the 'Integer' type is an object.
It means, that if you want to transform an array
to a List
type, you need objects, because you can't save primitive types into a List.