gpt4 book ai didi

java - ArrayList 字符串循环弄乱了字符串

转载 作者:行者123 更新时间:2023-11-29 05:01:18 26 4
gpt4 key购买 nike

我有一个名为 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);
}

如果您使用removeadd,您不仅会更改列表中元素的索引;还会更改列表中元素的索引。即使你让它工作它也非常低效,因为每次调用 remove 时都必须移动列表中的所有 元素。

关于java - ArrayList 字符串循环弄乱了字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32030878/

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