NullPointerException when trying to convert list back to array

I get NPE when I try to convert my list back to an array. I debugged and found that my list gets an extra value that is null.

Why is this happening and more importantly, how can I fix this problem?

List<String> attrList = new LinkedList<String>(Arrays.asList(attrArray)) //I loop through and remove unnecessary elements attrArray = attrList.toArray(attrArray); //next line uses attrArray and is throwing NPE. Here what I found through debugging, attrList = [1, 2, 3] attrArray = [1, 2, 3, null] 
+4
source share
1 answer

Try replacing

 attrArray = attrList.toArray(attrArray); 

with

 attrArray = attrList.toArray(new String[attrList.size()]); 

I think it will work, because now you have

 List<String> attrList = new LinkedList<String>(Arrays.asList(attrArray)); // I loop through and remove unnecessary elements attrArray = attrList.toArray(attrArray); 

and JavaDoc List#toArray(T[] a) states (highlighted by me):

If the list corresponds to the specified array with a spare number ( i.e., the array has more elements than the list ), the element in the array immediately after the end of the list is set to null . (This is useful in determining the length of the list only if the caller knows that the list does not contain any null items.)

+10
source

All Articles