java - How can I change an object if it is in an ArrayList? -
i have arraylist of dogs. if fluffy in arraylist, want change name fido. if not in arraylist, want add it, , change name fido.
so can check if fido exists in arraylist, how can retrieve can make changes? following closest have come. looking along lines of dogs.getelementequalto(new dog("fido"));
import java.util.arraylist; public class dog { public static void main(string[] args) { arraylist<dog> dogs = new arraylist<>(); dogs.add(new dog("fido")); dog dog = new dog("fido"); if (dogs.contains(dog)) { dog.name = "fluffy"; } system.out.println(dogs.get(0).name); //prints fido } string name; public dog(string name) { this.name = name; } @override public boolean equals(object o) { if (this == o) return true; if (!(o instanceof dog)) return false; dog dog = (dog) o; return !(name != null ? !name.equals(dog.name) : dog.name != null); } @override public int hashcode() { return name != null ? name.hashcode() : 0; } }
edit:
i tried changing main method this, did not work:
arraylist<dog> dogs = new arraylist<>(); dogs.add(new dog("fido")); dog dog = new dog("fido"); if (dogs.contains(dog)) { dogs.get(dogs.indexof(dog)).name = "fluffy"; } system.out.println(dogs.get(0).name);
you can (first) index of fido using:
int indexoffido = dogs.indexof(new dog("fido"));
and retrieve element using:
dogs.get(indexoffido);
however, depending upon concrete implementation of list
using, may more efficient iterate through list:
dog fido = new dog("fido"); (dog dog : dogs) { if (fido.equals(dog)) { // comparison way round, since // elements of list can null in general. // whatever. break; // unless want same instances of fido. } }
Comments
Post a Comment