iAz*_*ziz 0 java string android arraylist
我正在尝试从ArrayList中删除类似的字符串,但我收到此错误:
CurrentModificationException
Run Code Online (Sandbox Code Playgroud)
这是我的方法,我传递我的原始arrayList(旧)并获得一个没有冗余字符串的新列表.
ArrayList<String> removeRed(ArrayList<String> old) throws IOException
{
ArrayList<String> newList = new ArrayList<String>();
for (int i=0; i< old.size(); i++)
{
if(newList.size() < 1)
{
newList.add(old.get(0));
} else{
for(Iterator<String> iterator = newList.iterator(); iterator.hasNext();) {
while(iterator.hasNext())
{
if(!ChopMD((String) iterator.next()).equals(ChopMD(old.get(i))))
{
newList.add(old.get(i));
Log.e("new algo", "" + old.get(i) );
}
}
}
}
}}
Run Code Online (Sandbox Code Playgroud)
请注意,我的ChopMD()返回一个特定的字符串,它工作正常.它适用于前几个字符串,它抛出异常.任何解决此问题的建议都将受到赞赏.谢谢.
如果您使用标准库没有问题(总是更好,为什么重新发明轮子)尝试
List<String> uniques = new ArrayList<String>(new HashSet<String>(oldList));
Run Code Online (Sandbox Code Playgroud)
在HashSet将只包含唯一的字符串和ArrayList构造采取任何Collection(包括HashSet),从建立一个列表.
从您的评论来看,您似乎正在尝试使用ArrayList 实现具有唯一键的关联数组.更好的方法是使用像HashMap这样的Map实现来将ID与其关联的字符串配对.
Map<Integer, String> map = new HashMap<>();
map.put(1, "This string corresponds to ID=1");
map.put(3, "Donald Ducks Nephews");
map.put(7, "Is a Prime");
Run Code Online (Sandbox Code Playgroud)
然后获取与ID关联的值:
int key = someObject.getID();
String value = map.get(key);
Run Code Online (Sandbox Code Playgroud)
所有Map实现都使用唯一键,因此您无需检查冗余ID,如果您尝试添加新的(键,值)对,则在映射包含键时将替换与ID关联的值.
map.put(1, "New String");
String s = map.get(1); //s will no longer be "This string corresponds to ID=1"
Run Code Online (Sandbox Code Playgroud)
如果您不想要这种行为,您可以选择将其中一个Map实现子类化为忽略,.put(key, value)如果地图包含key,value或委托.put(key,value)给其他类.
子类:
public class UniqueValueHashMap<K,V> extends HashMap<K, V>{
@Override
public V put(K key, V value) {
if (containsKey(key))
return null;
return super.put(key, value);
}
Run Code Online (Sandbox Code Playgroud)
委派
public class SomeClass {
private Map<Integer, String> map = new HashMap<>();
// ...stuff this class does
public String put(int key, String value) {
if (map.containsKey(key))
return null;
return map.put(key, value);
}
// ...more stuff this class does
}
Run Code Online (Sandbox Code Playgroud)
委派是更好的方法,请注意如何在不引入覆盖.put(key,value)TreeMap 的新类的情况下更改地图实现(可能使用TreeMap而不是HashMap).
| 归档时间: |
|
| 查看次数: |
808 次 |
| 最近记录: |