Replacing an object in an ArrayList

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

I have a list of arrays named ArrayList<Animal> . This list contains only 5 animals listed.

 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 I will take an object from this list of arrays and modify it.

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

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

Note. I do not know the index to which this object is added.

+7
source share
5 answers

Look at the bell column for how to do this with an ArrayList . However, you probably will 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); 
+1
source

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

If you just want to change the animal that is already in the set, you do not need to do anything with this list, because what is stored in the list is a reference to an object, not a copy of the object.

+7
source

You must first get its link from the list and just change it. Like this:

 Integer yourId = 42; for (Animal a : animalList){ if (a.getId().equals(yourId)){ a.setName("Brown Lion"); //... break; } } 
+6
source
 for(Animal al: a){ if(al.getName().equals("Lion")){ al.setName("Brown Lion"); al.setId(1); break; } } 
  • Scroll until you find Animal
  • change its attributes
  • break outta loop
+2
source

You can easily use HashMap. Your key is id, and the value is an animal object.

using the get method, you can take the animal object that you need and modify it and place the new Animal again against the same key.

+1
source

All Articles