Marcelo Ruiz
Marcelo Ruiz

Reputation: 393

Is there a way to get (know) all objects created from a class in the same class?

If I create a class A with some properties for example a, b, c and I create objects A x1; A x2; A x3; ... A xN. Is there a way I can create a method in the same class that retrieves all objets that I create? I want to create something like static ArrayList <A> to add them but I think I cannot be done it in the same class.

Upvotes: 0

Views: 165

Answers (2)

Eric
Eric

Reputation: 97581

Yes, by simply recording that you created them:

class A {
    private static List<A> instances = new ArrayList<A>();

    public A() {
        instances.add(this)
    }

    public static List<A> getInstances() {
        return Collections.unmodifiableList(instances);
    }
}

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691735

public class A {
    private static List<A> createdAs = new ArrayList<>();

    public A() {
        synchronized(createdAs) {
            createdAs.add(this);
        }
    }
}

But, as Luiggi says, this is probably a very bad idea, and there's probably a much cleaner way to solve your problem. One big problem this causes, for example, is that it causes a memory leak: none of the created As can be garbage-collected, even if nobody uses them anymore, since they're all referenced by the static list.

Upvotes: 2

Related Questions