I am trying to check if my array has a given element or not. For this, I am converting that array to list and then using contains. But, I am getting this strange behavior.
int[] arr = null;
System.out.println(Arrays.asList(arr).contains(1)); //output as false
System.out.println(Arrays.asList(null).contains(1)); //nullPointerException
Why the first one is not throwing NPE? Please suggest.
3 Answers 3
Primitive represent value and object variable represent reference. null is a keyword in java and it is used to denote absence of something or reference of nothing. If you create object like
Object obj=new Object(); or Integer i=new Integer();
Heap memory assign some space for reference variable obj and i. when you assign obj=null; or i=null; this means obj and i will not point to that memory or any of it.
int[] arr=null;
Here arr is a primitive variable,and its value is null.
When you try to convert array to list by Arrays.asList(arr) your passing empty array but your passing.
Because
public static <T> List<T> asList(T... a) {
return new ArrayList<T>(a);
}
asList() method take varargs array and return list.
When you write
System.out.println(Arrays.asList (arr).contains(1)); //output as false
means your actually comparing 1 from the returned list and contains(1) method check whether the 1 is present or not in list.
But in second statement System.out.println(Arrays.asList (null).contains(1));
your passing null.
asList(null) method try to
return new ArrayList<T>(a);
that means return statement calling to
ArrayList(E[] array) {
if (array==null)
throw new NullPointerException();
a = array;
}
and in second statement you pass null.
In case, Integer[] arr = null; your actually creating object of Integer wrapper class and object variable represent reference, here arr is object and it is referring to null.And null means reference of nothing.So, that's the reason why System.out.println(Arrays.asList(null).contains(1)); throw NPE
About null in java you can visit this link for more details : 9 Things about Null in Java
Comments
Java primitive types do not work with Arrays.asList(T...); this is masked because of the array (which is a valid type T, so a List of int[]). You want the corresponding wrapper type. Something like,
Integer[] arr = { 1 };
System.out.println(Arrays.asList(arr).contains(1));
which outputs (as expected)
true
Comments
Implementation of Arrays.asList() method is : Check Here
public static <T> List<T> asList(T... array) {
return new ArrayList<T>(array);
}
That's why, you cannot contract like new ArrayList<int>() with primitive datatype int.
If so, if you change your source int to Integer
Integer[] arr = null;
System.out.println(Arrays.asList (arr).contains(1)); ///nullPointerException
System.out.println(Arrays.asList(null).contains(1)); //nullPointerException
List<int[]>. The second is trying to build a list (List<Object>) from the varargs array, but the array is null and causes NPE.