Keeping track of all objects of a class

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

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

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.

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.

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật