Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question
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 '13 at 2:52
2  
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 '13 at 8:27
1  
"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 '13 at 15:19

4 Answers 4

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 centralize 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.

share|improve this answer
    
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 '13 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. –  user61852 Jun 11 '13 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 '13 at 5:33
    
A singleton technically would hold all instances I guess. The one single instance. –  Rig Dec 19 '13 at 12:56

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.

share|improve this answer
1  
You can directly write static ArrayList<ListeStatic> list = new ArrayList<ListeStatic>(); ans supress the statc {..} –  cl-r Jun 11 '13 at 7:33
2  
In Java method's name begins with a lowercase letter : uptdateAll(){..;} –  cl-r Jun 11 '13 at 8:00
    
oops... it's been a while since I've aired my java in public –  Kelly Thomas Jun 11 '13 at 8:41
    
@KellyThomas A car adding itself to a list, them removing itself from it. Sounds unnatural. –  user61852 Jun 11 '13 at 14:37

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.

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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