gpt4 book ai didi

java - Arraylist 中的空指针异常

转载 作者:行者123 更新时间:2023-12-01 23:13:47 27 4
gpt4 key购买 nike

即使我已经放置了空检查,我仍然收到空指针异常:

@Override 
public ArrayList<DataCache> getData()
{
if(contentOf != null)
{
StoreData data = new StoreData(this);
if(data!=null)
{
ArrayList<DataCache> cacheOf = null;
System.out.println("Size of ContentOf"+contentOf.size());
for (int i=0;i<contentOf.size();i++)
{
System.out.println("Value of ContentOf"+contentOf.get(i).mFeed);
ArrayList<DataCache> cache = contentOf.get(i).mFeed.getData();
if (cache != null)
cacheOf.add(cache.get(i));
}
return cacheOf;
}
}
}

异常(exception):

02-03 10:19:18.770: E/AndroidRuntime(8680): FATAL EXCEPTION: main
02-03 10:19:18.770: E/AndroidRuntime(8680): java.lang.NullPointerException
02-03 10:19:18.770: E/AndroidRuntime(8680): at
com.activity.MainFragmentActivity.getData(MainFragmentActivity.java:198)

最佳答案

在添加元素之前还需要初始化cacheOf ArrayList:

ArrayList<DataCache> cacheOf = new ArrayList<DataCache>(); //initialize here
System.out.println("Size of ContentOf"+contentOf.size()); //This will be zero.
for (int i=0;i<contentOf.size();i++) {
//..your code here...
if (cache != null){
if(i<=cache.size())
cacheOf.add(cache.get(i));
}
}

关于java - Arraylist 中的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21531174/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com