作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个名为 PhotoArrayList 的 ArrayList。它包含诸如“picture1.jpg、picture2.png、picture3.gif 等”之类的字符串。这个 ArrayList 中大约有 50 或 60 个字符串。我需要在开头添加他们文件夹的路径,例如“mnt/sdcard0/Pictures/picture1.jpg 等”。所以,我正在使用以下代码
Integer PhotoFileAmount = PhotoArray.length; //PhotoArray and PhotoArrayList are same
for(int i=0; i < PhotoFileAmount; i++){
String PhotoFileAndPath = (PhotoFolder + '/' + PhotoArrayList.get(i));
PhotoArrayList.remove(PhotoArrayList.get(i));
PhotoArrayList.add(PhotoFileAndPath);
}
但是我得到了一个奇怪的结果。 PhotoArrayList 的开头没有变化,中间部分没问题,最后一部分两次获取路径。比如“picture1.jpg, mnt/sdcard0/Pictures/picture2.png, mnt/sdcard0/Pictures/mnt/sdcard0/Pictures/picture3.gif
最佳答案
如果你想改变一个ArrayList
的元素,使用set
为给定位置的元素分配新值的方法:
int PhotoFileAmount = PhotoArray.length; // use int here to avoid unnecessary boxing / unboxing
for(int i=0; i < PhotoFileAmount; i++){
String PhotoFileAndPath = (PhotoFolder + '/' + PhotoArrayList.get(i));
PhotoArrayList.set(i, PhotoFileAndPath);
}
如果您使用remove
和add
,您不仅会更改列表中元素的索引;还会更改列表中元素的索引。即使你让它工作它也非常低效,因为每次调用 remove
时都必须移动列表中的所有 元素。
关于java - ArrayList 字符串循环弄乱了字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32030878/
我是一名优秀的程序员,十分优秀!