Replacing an object in a ArrayList

arraylist, java

Solution

Look at bellum's post for how to do this with an `ArrayList`. However, you'd probably be better off with a `HashMap<String, Animal>`

HashMap<String, Animal> animals = new HashMap<String, Animal>();
// ...
Animal animal = new Animal();
animal.setName("Lion");
animal.setId(1);
animals.put(animal.getName(), animal);

// to modify...

Animal lion = animals.remove("Lion"); // no looping, it finds it in constant time
lion.setName("Brown Lion");
animals.put(animal.getName(), animal);

Problem

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.

Original source