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.
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With