Android 从SharedReferences向arraylist添加项时发生IndexOutOfBoundsException
我的arraylist有点问题,我需要一个解决方法来避免IndexOutOfBoundsException异常 以下是我添加项目的方式:Android 从SharedReferences向arraylist添加项时发生IndexOutOfBoundsException,android,exception,arraylist,sharedpreferences,indexoutofboundsexception,Android,Exception,Arraylist,Sharedpreferences,Indexoutofboundsexception,我的arraylist有点问题,我需要一个解决方法来避免IndexOutOfBoundsException异常 以下是我添加项目的方式: for(Map.Entry<String,?> entry : getAll().entrySet()){ // this is a map with all my sharedprefs list.add((Integer) entry.getValue(), myItem); } 它抛出异常,因为它需要从0开始
for(Map.Entry<String,?> entry : getAll().entrySet()){ // this is a map with all my sharedprefs
list.add((Integer) entry.getValue(), myItem);
}
它抛出异常,因为它需要从0开始
有人有办法吗?谢谢问题是您无法访问
数组列表中尚不存在的索引
,由于Map
没有排序,您可能试图在拥有有效元素索引0
之前在索引1
处插入,或者在拥有有效索引0
和1
之前在索引2
处插入
编辑:
您可以使用
ArrayList<String> arr = new ArrayList<String>(getAll().entrySet());
arraylistarr=newarraylist(getAll().entrySet());
然后使用循环,这个问题的“解决方法”是在开始添加到特定位置之前,用所有0或其他值预先填充列表。例如:
int mapSize = mPrefMap.size();
for(int i = 0; i < mapSize; i++){
listOfStuff.add(0);
}
int-mapSize=mPrefMap.size();
对于(int i=0;i
添加一个等于首选项贴图大小的数字0将基本上将这些位置的所有位置初始化为0。然后,您可以返回并以您现在的方式添加特定的值
我仍然不明白为什么您不只是使用标准的SharedReference
类。这将避免使用这种变通方法,并节省您为ArrayList
设置默认值所浪费的时间 在这里定义列表
。它是一个简单的数组列表。它不会扔npe!尝试执行ArrayList arr=new ArrayList()代码>为什么不直接使用SharedReference
?当有一个非常好的类来完成您正在尝试完成的工作时,此“解决方案”似乎不必要地复杂。MAP条目将按自然顺序获取值。。字母顺序..这正是问题所在,它试图在“0”之前添加“1”
ArrayList<String> arr = new ArrayList<String>(getAll().entrySet());
int mapSize = mPrefMap.size();
for(int i = 0; i < mapSize; i++){
listOfStuff.add(0);
}