0

please see the code below.

int[] intArray={1,2,3,4,3,4,5};
    List intList=Arrays.asList(intArray);
    System.out.println(intList.contains(1));

Above code is returning false.can any one pls explain why it is so?

RSingh
  • 171
  • 2
  • 11
  • 2
    You should never use raw types like `List`. If you had written `List`, you'd have noticed that the code wouldn't compile anymore. Because `Arrays.asList` with a primitive integer array will return just a List with a single element, the array; not a list made of all the elements of the array. – Tunaki Mar 07 '16 at 09:36
  • Why the -2? For someone coming from say C++, this is not at all obvious. And the question text contains all that is necessary for an answer. – Bathsheba Mar 07 '16 at 09:51
  • @Bathsheba thanks sir,After seeing -2 I thought I asked the wrong question,i am novice to java. – RSingh Mar 07 '16 at 10:02

1 Answers1

0

Arrays.asList converts your primitive array to a List<int[]> whose single element is the array, intList.contains(intArray) would return true, but intList.contains(1) won't.

If you change your int[] array to Integer[], you'll get your expected output - i.e. a List<Integer> that contains the elements of the original array.

Eran
  • 359,724
  • 45
  • 626
  • 694