Uni835
Uni835

Reputation: 27

ArrayList string loop mess up strings

I've got an ArrayList called PhotoArrayList. It contains strings like "picture1.jpg, picture2.png, picture3.gif etc." There is like 50 or 60 strings in this ArrayList. I need to add path of their folder in the beginning like "mnt/sdcard0/Pictures/picture1.jpg etc." So, I'm using following code

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);
       }

But I'm getting a strange result. The beginning of PhotoArrayList is unchanged while it's middle part is okay and last part gets the path twitce. Like "picture1.jpg, mnt/sdcard0/Pictures/picture2.png, mnt/sdcard0/Pictures/mnt/sdcard0/Pictures/picture3.gif

Upvotes: 1

Views: 162

Answers (2)

Sound Conception
Sound Conception

Reputation: 5411

ArrayList.add(E Object) adds the Object at the at the end of the list.
You are currently removing an item from where ever it is in the list, then adding a new version at the end of the list. As i approaches PhotoFileAmount your .get(i) statement is going to start retrieving the revised objects that you have added at the end.

Upvotes: 1

fabian
fabian

Reputation: 82461

If you want to change elements of a ArrayList, use the set method to assign a new value to the element at a given position:

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);
}

If you use remove and add you not only change the indices of the elements in the list; even if you make it work it's very inefficient, since all remaining elements in the list have to be moved every time remove is called.

Upvotes: 2

Related Questions