LonelyPenguin LonelyPenguin - 1 month ago 5
Java Question

How do you program without knowing how many objects you will need in advance?

In Java, it seems as if you must know how many objects your program will have: Every object must have a name, and you can't use variables (like

String
s or
int
s) for the name.

What if I have to create some new objects, but I dont know how many and maybe later I will have to create new ones. Is this impossible?

For example, if I am writing a program to register new cars, but I don't know how many nor when they will show up. How would I do this?

Answer

Arrays are the most basic mechanism for this purpose:

int numObj = 15; // can be any number determined at runtime
int[] myArray = new int[numObj];

Apart from arrays, there are several more collection types you can use to store dynamic data: lists (such as ArrayList<>), maps, sets, trees, etc. They all serve specific purposes, but what they have in common is that they store objects while eliminating the need to give unique names to them.

Arrays and ArrayList enables you to access contained objects by number, while a map such as a TreeMap<> lets you access objects using a key such as a String – so you could access cars by owner name, for example.

With collections other than the basic array, you specify the contained type (called template type) in angle brackets after the collection type, e.g. an ArrayList<MyObject> stores only MyObjects and an ArrayList<Comparable> stores only objects which implement the Comparable interface.