[Solved] ArrayList for handeling many Objects?


If you have constant pool of Excersises, and you only need to access them by index, then you can use array instead:

Excersise[] excersises = new Excersise[EXCERSIZE_SIZE];
//fill excersises
//use excersises
workout.add(excersises[index]);

ArrayList is designed to have fast access to element by index, and it is using array underneath, but it has range check inside it’s get method. On the other hand ArrayList provide a bunch of useful methods, in case if you need any of them. The other thing is that if you would like to hold a lot of objects in it it might be wise to create it with some capacity, which you expect, knowing of how many objects you will add to this ArrayList, for example if you expect 1000 objects then you can do:

List<Excersise> excersises = new ArrayList(1000);

In that way you’ll omit recreating of arrays inside ArrayList.add method when array inside ArrayList will not be able to store provided value (HashMap also has constructor HashMap(int initialCapacity)).

If you would like to access to excersise for example by it’s symbolic name, let’s say “push ups”, then you can use HashMap:

Map<String, Excersise> excersiseByName = new HashMap<>();
//fill excersises
workout.add(excersiseByName.get("push ups"));

3

solved ArrayList for handeling many Objects?