10

I'm new to object-oriented programming, and I keep running into this issue. (I'm programming in Java) I've been a bit reluctant to ask about this, since it seems like such a basic issue, but I can't find any information on it, or questions about it here, and none of the textbooks I have read (on a quite basic level of course) have touched on this issue:

Often I need to keep track of all objects of a class that have been created, to iterate through them for various purposes. They way I currently write programs, many objects are only referenced from other objects, meaning I have no array or collection with which to reference them all.

I imagine that, as this seems like such a very basic necessity in OOP, there should be a quite institutionalized, and simple, way to go about this? Is it usual practice to keep a separate list of all the objects of a class?

I thought about a static array or collection, to which through its constructor, every new object created would be added. This however would not work with subclasses, since constructors are not inherited?

I realize this question might not have one easy answer; I just hope someone can enlighten me a bit on this subject. I feel like if I'm lacking a central piece of knowledge here.

3
  • 5
    A more specific example of the tracked and the tracker might help. This problem is handled many different ways depending on the context, how they are used, and so on.
    – JustinC
    Jun 11, 2013 at 2:52
  • 3
    I think you might be approaching the problem from the wrong end. It is not very common to need a list of all the instances of a given class, and having one would cause all sorts of design problems (because now even instances created in totally unrelated contexts depend on each other through this list).
    – tdammers
    Jun 11, 2013 at 8:27
  • 2
    "iterate through them for various purposes" ... such as ... ? Generally, an object has one 'owner' (not a formal term, more just a statement about program semantics), and it's not for anyone else to have 'various purposes' with the object.
    – AakashM
    Jun 11, 2013 at 15:19

4 Answers 4

10

I don't know why you need to keep a list of all instances of a class.

That would cause memory leakage since those objects will never be disposed of, since the list will still be referencing them after no other class does.

But if you really want to follow that route:

  1. Use the Factory pattern. A factory class with methods that instanciate the class and return the objects. That way you have a centralized point to control the instantiations.
  2. Use the Singleton pattern to hold a list or lists that hold the instances.
  3. Make the factory put each object of a certain type in a list after creating them.

By the way: constructors are inherited.

4
  • You can of course give the factory a "dispose" method that removes the instance from its list of tracked instances. But there's no way of explicitly invoking it. Or give the instance a dispose method that triggers the dispose method in its factory, which has the same drawback but is slightly more likely to be actually called as it's closer to the user, more visible.
    – jwenting
    Jun 11, 2013 at 6:22
  • @jwenting Of course that's a way. But that would create ugly, unnecessary dependencies between the classes and the factory. Classes should know nothing about the factory that creates them. Jun 11, 2013 at 14:32
  • hence having the factory keep track of what it creates, rather than the object telling the factory to register it...
    – jwenting
    Jun 12, 2013 at 5:33
  • A singleton technically would hold all instances I guess. The one single instance.
    – Rig
    Dec 19, 2013 at 12:56
4

Try to think context. When you create an object, you do so in a certain context. For example, if your game is about shooting aliens, your app will be creating new Alien objects all the time. They will be displayed in a field called Space (which could be the class that represents the main UI).

It is perfectly natural for Space to have a property named currentAliens, which would be an array, to which you add each new alien you create. If you want to allow your user to rip apart the fabric of spacetime and destroy all aliens at once, you would iterate through that collection and destroy each object.

If you wanted to have access to this collection of aliens from within other parts of your app (say, from a Settings page, where you might want to allow users to wipe out certain types of alien in one fell swoop), your Settings context would need to be given access to the Space object.

3

It should be noted that weak references can be used in combination with the other given solutions to allow the garbage collector to dispose of tracked objects when they are no longer referenced elsewhere. This eliminates memory leaks without requiring code elsewhere to manually dispose of objects, or otherwise care that they are being tracked. You can provide a ReferenceQueue to receive notification of references to objects that have been freed.

I thought about a static array or collection, to which through its constructor, every new object created would be added. This however would not work with subclasses, since constructors are not inherited?

The constructors of base classes are invoked before constructors of derived classes. Every class has at least one constructor and constructors cannot be overridden.

2

When making games people sometimes want a "self managing" collection of each type of game object.

One implementation looks like this:

public class Car {

    static ArrayList<Car> list = new ArrayList<Car>();

    public Car() {
        list.add(this);
    }

    void kill() {
        list.remove(this);
    }

    static public void updateAll()
    {
        for (int i = list.size() - 1; i >= 0; i--)
        {
                list.get(i).update();
        }
    }

    public void update()
    {
        //update logic
    }
}

In this manner methods manipulating the collection can be declared static while non-static methods manipulate an instance (updateAll vs. update).

While fine for very simple scenarios, with even moderate complexity it is usually best to create separate manager classes.

6
  • 1
    You can directly write static ArrayList<ListeStatic> list = new ArrayList<ListeStatic>(); ans supress the statc {..}
    – cl-r
    Jun 11, 2013 at 7:33
  • 2
    In Java method's name begins with a lowercase letter : uptdateAll(){..;}
    – cl-r
    Jun 11, 2013 at 8:00
  • oops... it's been a while since I've aired my java in public Jun 11, 2013 at 8:41
  • @KellyThomas A car adding itself to a list, them removing itself from it. Sounds unnatural. Jun 11, 2013 at 14:37
  • 1
    @CayetanoGonçalves as a static field it is one list shared by all instances. Jun 8, 2018 at 18:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.