1

I would like to know if is it expensive in terms of resource usage to declare a static field to keep track of all istances of that class in a class that I need to istantiate thousand of times. I usually make another class like the example below, but I wonder if I could make everything more compact without wasting resources.

1

public class Object {
    public static List<Object> objects = new ArrayList<>();
    public Object() {
        objects.add(this);
    }
    //My code
}

2

public class Object {
    public Object() {
        ObjectManager.addObject(this);
    }
    //My code
}

public class ObjectManager {
    private static List<Object> objects = new ArrayList<>();
    public static void addObject(Object obj) {
        objects.add(obj);
    }
}

What's the difference between these 2 methods?

Leo
  • 92
  • 8
  • 1
    Nothing, basically. The very slight cost of having an extra class, but that's all. – Jon Skeet Oct 30 '16 at 08:58
  • 2
    The main difference between the two is that, with the first, anybody can call `Object.objects.clear()`, potentially screwing it up for everywhere else that needed the contents. – Andy Turner Oct 30 '16 at 09:03
  • Do you want to know only the count of how many objects created ? – Vasu Oct 30 '16 at 09:22

1 Answers1

0

There is no practical difference between your examples except visibility of "objects" field.

PS: your code will lead to memory leak because you never remove objects from list.

talex
  • 17,973
  • 3
  • 29
  • 66