Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException when trying to convert list back into an array

I'm getting a NPE when trying to convert my list back into an array. I debugged through and found that my list is getting an extra value that is null.

Why is the happening and more importantly how do I fix the issue?

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's what I found through debugging,

attrList = [1, 2, 3]

attrArray = [1, 2, 3, null]
like image 342
mr_fruitbowl Avatar asked Dec 27 '22 09:12

mr_fruitbowl


1 Answers

Try replacing

attrArray = attrList.toArray(attrArray);

with

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

I think it will work, because what you have right now is

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

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

If the list fits in the specified array with room to spare (i.e., the array has more elements than the list), the element in the array immediately following 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 elements.)

like image 125
jlordo Avatar answered Dec 28 '22 22:12

jlordo