ArrayList is a wrapper class for dynamically resizing array. While plain array provides only "setter", "getter" and "length" methods, ArrayList provides this and much more.
Suppose, you have Cat [] catArray and List<Cat> catList. (See below, why List and not ArrayList).
- Setter: instead of
catArray[i] = someCat use catList.set(i, someCat)
- Getter: instead of
someCat = catArray[i] use someCat = catList.get(i). Getter returns Cat, so you can call methods on returned object as this: catList.get(i).meow();
- Size:
catArray.length becomes catList.size()
List also provides such methods as add (insert element at position or append to the end of the list), remove (delete element from list), indexOf to search element, etc.
The biggest advantage of ArrayList comparing to plain array is that it is resizable. You don't need to specify fixed size in advance, ArrayList will grow as you add elements and shrink as you remove them.
This resizing nature of List also implies the main difference between these two structures. When working with Arrays, you used to create array of fixed length and then set it's elements one by one:
Cat[] cats = new Cat[10];
for (int i = 0; i < cats.length; i ++) {
cats[i] = new Cat(); // populate cat #i
}
With lists you usually create empty list and then add elements to it. You don't need to care about size, as list grows as you add elements:
List<Cat> cats = new ArrayList<Cat>();
// we want to add 10 cats
for (int i = 0; i < 10; i ++) {
cats.add(new Cat()); //add new cat to the end of the list
}
Regarding the declaration List<Cat> cats = new ArrayList<Cat>();. In java it is considered good practice to declare variable as the least concrete interface as practical. For lists it's usually Collection or List. However it will not be a mortal mistake if you declare your cats as ArrayList<Cat> cats = new ArrayList<Cat>();
I intentionally omitted many aspects of Arrays vs Lists, including primitives, performance, generics. Internet is full of articles that can provide more details if OP is interested.
.-- try usingcats.get(i)to get theCatinstance at positioniin the collection (rather thatcats get(i))..there so I didn't know I need one. Thanks!