我有一个foreach循环遍历向量中的每个对象.当我调试代码时,它成功运行向量中的第一个对象.但是当它试图为第二个对象运行循环时它会失败.我确信矢量中有多个元素.
for(Object shape : vecForShapes)
{
currentNode = (Drawable) shape;
newNode = getResources().getDrawable(R.drawable.nodered);
newNode.setBounds(currentNode.getBounds());
vecForShapes.remove(currentNode);
vecForShapes.add(newNode);
}
Run Code Online (Sandbox Code Playgroud)
基本上我的问题是,为什么这个循环失败了?我真的不明白这里有什么问题.
PS我的最终目标是currentNode从矢量中删除,newNode然后替换它,然后在我的onDraw方法中重绘整个矢量.
谢谢
您无法从迭代中删除或添加对象.vecForShapes.remove(currentNode);例如修改vecForShapes.这样你就得到了例外.
如果我是你,我会做你想要的修改:
for (int i = 0; i < vecForShapes.size(); i++) {
currentNode = (Drawable) shape;
newNode = getResources().getDrawable(R.drawable.nodered);
newNode.setBounds(currentNode.getBounds());
vecForSahpes.set(i, newNode);
}
Run Code Online (Sandbox Code Playgroud)
这应该做你想要的没有任何错误.
PS:你真的是这个意思Vector吗?我认真推荐使用ArrayList.它的性能明显更好.
| 归档时间: |
|
| 查看次数: |
1924 次 |
| 最近记录: |