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]
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With