0
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?

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
  • `Arrays.asList(AllCards)` returns a `List`, hence it can´t find a single value in the `List`. The reason behind it can be read [here](http://stackoverflow.com/questions/12020886/how-arrays-aslistint-can-return-listint) – SomeJavaGuy Oct 29 '15 at 12:58

4 Answers4

2
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

Community
  • 1
  • 1
Tahar Bakir
  • 716
  • 5
  • 14
  • thank you! how can i see if a array contains that number twice? – user1806846 Oct 29 '15 at 13:48
  • if(Collections.frequency(Arrays.asList(AllCards), 1) == 2) ==> This will check if the number 1 is present twice ( of course you need to replace 1 with the number you are looking for.) – Tahar Bakir Oct 29 '15 at 13:55
1

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);
Tom
  • 16,842
  • 17
  • 45
  • 54
wero
  • 32,544
  • 3
  • 59
  • 84
0

Problem is that 1 is autoboxed as an Integer not an int.

Change declaration to Integer[]

Fran Montero
  • 1,679
  • 12
  • 24
0

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.

xFunkyTImes
  • 117
  • 9