简体   繁体   English

为什么非空列表会引发空指针异常?

[英]Why does a non-empty List throw a Null Pointer Exception?

I have an List array 'details'. 我有一个列表数组“细节”。

List<HistoryDetails> details

where HistoryDetails is an object containing strings. 其中HistoryDe​​tails是包含字符串的对象。

When I check the size it gives me a positive value. 当我检查尺寸时,会给我一个正值。

details.size()

But when I try to access an element it throws a null pointer exception. 但是,当我尝试访问元素时,它将引发空指针异常。

details.get(0).getFirstElement();


Attempt to invoke virtual method 'java.lang.String com.HistoryDetails.getFirstElement()' on a null object reference

I am invoking the element at the very next line to where I check the size. 我正在检查尺寸的下一行调用元素。 Hence, nothing should be reset. 因此,不应重置任何内容。 What could be wrong? 有什么事吗

It looks like details is a List , but the first element of the List is null. 它看起来像details是一个List ,但的第一个元素List为空。 That is, it looks like details.get(0) == null . 也就是说,它看起来像details.get(0) == null

A List details having many items can have first item a null object. 具有许多项目的列表details可以使第一个项目为空对象。 before using that item check null. 使用该项目之前,请检查null。

if(details.get(0)!=null){
details.get(0).getFirstElement();
}

因为它包含null。

Log.d("TEST", details.get(0)); //should return null

This will avoid the null pointer exception: 这将避免空指针异常:

if (!details.isEmpty()) {
    details.get(0).getFirstElement();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么这会引发Null Pointer Exception? - Why does this throw Null Pointer Exception? 为什么在空字符串上“拆分”会返回一个非空数组? - Why does "split" on an empty string return a non-empty array? 在 javac 源代码中,为什么closure(Type) 会为非类/接口类型返回一个非空列表? - In the javac source code, why does closure(Type) return a non-empty list for non-class/interface types? 为什么 java.util.Map.containsKey 会为不支持空键的映射抛出空指针异常? - Why does java.util.Map.containsKey throw a null pointer exception for maps which don't support null keys? 如何使用空列表而不是 null 抛出自定义异常? - How to throw custom exception with empty list instead of null? ConcurrentModificationException:如果它不是第一个变量,为什么在 List 中删除 null 会引发此异常 - ConcurrentModificationException: Why does removing the null in List throw this Exception if it´s not the first variable 为什么contains()方法在Java中的非空字符串中找到空字符串 - Why does contains() method find empty string in non-empty string in Java 为什么这会导致空指针异常? - Why does this cause a null pointer exception? 为什么在HashSet中添加null不会引发异常,而在TreeSet中添加null会引发异常 - Why adding null in HashSet does not throw Exception,but adding null in TreeSet throw Exception 为什么Null Pointer Exception对象的原因字段为空? - Why do Null Pointer Exception objects have an empty cause field?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM