vendredi 20 mars 2020

Java: How to delete an object from multiple lists at once

I have multiple lists and multiple objects, e.g.:

class Example {
  public static void main(String[] args) {
    Dog dog1 = new Dog("MyDog1", 5);
    Dog dog2 = new Dog("MyDog2", 2);
    Dog dog3 = new Dog("MyDog3", 7);

    List<Dog> list1 = new ArrayList<>();
    list1.add(dog1);
    list1.add(dog2);
    list1.add(dog3);

    List<Dog> list2 = new ArrayList<>();
    list2.add(dog1);
    list2.add(dog2);
    list2.add(dog3);

    List<Dog> list3 = new ArrayList<>();
    list3.add(dog1);
    list3.add(dog2);
    list3.add(dog3);

    List<Dog> list4 = new ArrayList<>();
    list4.add(dog1);
    list4.add(dog2);
    list4.add(dog3);

    List<Dog> list5 = new ArrayList<>();
    list5.add(dog1);
    list5.add(dog2);
    list5.add(dog3);
  }
}

class Dog {
  private String name;
  private int age;

  public Dog(final String name, final int age) {
    this.name = name;
    this.age = age;
  }
}

Now I want to remove dog1 from all lists, without iterating over all lists (in production I have a large amount off lists and "dogs"). Maybe it is possible to remove all references using reflections, but I did not found something like that in the internet.

//Edit: It is about deleting the object so the memory is freed. And I do NOT want to delete it manually from all lists with list.remove(dog1);





Aucun commentaire:

Enregistrer un commentaire