mr_*_*owl 4 java arrays list nullpointerexception
我试图将我的列表转换回数组时得到一个NPE.我通过调试,发现我的列表获得了一个空值的额外值.
为什么会发生这种情况,更重要的是如何解决问题?
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]
Run Code Online (Sandbox Code Playgroud)
jlo*_*rdo 10
尝试更换
attrArray = attrList.toArray(attrArray);
Run Code Online (Sandbox Code Playgroud)
同
attrArray = attrList.toArray(new String[attrList.size()]);
Run Code Online (Sandbox Code Playgroud)
我认为它会起作用,因为你现在拥有的是
List<String> attrList = new LinkedList<String>(Arrays.asList(attrArray));
// I loop through and remove unnecessary elements
attrArray = attrList.toArray(attrArray);
Run Code Online (Sandbox Code Playgroud)
List#toArray(T[] a)和州的JavaDoc (由我突出):
如果列表适合指定的数组,并且有空间(即,数组的元素多于列表),则紧跟在列表末尾的数组中的元素将设置为
null.(仅当调用者知道列表不包含任何null元素时,这在确定列表长度时很有用.)
| 归档时间: |
|
| 查看次数: |
1136 次 |
| 最近记录: |