Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing an object in a ArrayList

Tags:

java

arraylist

I need to know how to replace an object which is in a ArrayList<Animal>.

I have a array list called ArrayList<Animal>. This list only has 5 animals listed init.

Animal animal = new Animal();
animal.setName("Lion");
animal.setId(1);

ArrayList<Animal> a = new ArrayList<Animal>();

a.put(animal); // likewise i will be adding 5-6 animals here.

Later on, i will take an object from this array list and modify it.

Animal modifiedAnimal = new Animal();
 animal.setName("Brown Lion");
    animal.setId(1);

Now i need to add this Animal Object to the ArrayList<Animal> a array list. I need it to replace the previous Animal object which we named it Lion. How can i do this ?

Note: I don't know the Index where this object is added.

like image 514
user1315906 Avatar asked Dec 05 '12 16:12

user1315906


2 Answers

If you really want to replace the Animal in the list with a whole new Animal, use List#set. To use List#set, you'll need to know the index of the Animal you want to replace. You can find that with List#indexOf.

If you just want to modify an animal that is already in the set, you don't have to do anything with the list, since what's stored in the list is a reference to the object, not a copy of the object.

like image 53
T.J. Crowder Avatar answered Oct 07 '22 05:10

T.J. Crowder


You must first get its reference from list and simply modify it. Like this:

Integer yourId = 42;

for (Animal a : animalList){
     if (a.getId().equals(yourId)){
          a.setName("Brown Lion");
          //...
          break;
     }
}
like image 43
bellum Avatar answered Oct 07 '22 05:10

bellum