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