Reputation: 3494
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.
Upvotes: 7
Views: 13544
Reputation: 3710
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;
}
}
Upvotes: 6
Reputation: 32323
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);
Upvotes: 2
Reputation: 46408
for(Animal al: a){
if(al.getName().equals("Lion")){
al.setName("Brown Lion");
al.setId(1);
break;
}
}
Upvotes: 2
Reputation: 6572
You could use HashMap for this easily. Your key is id and value is animal object.
by using get
method you can take the animal object you required and do the modification and again put new Animal against same key.
Upvotes: 1
Reputation: 1074138
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.
Upvotes: 7