So, lets get started!!!
The java.util.ArrayList class is one of the most commonly used of all the classes in the Collections Framework. Some of the advantages ArrayList has over arrays are
• It can grow dynamically.
• It provides more powerful insertion and search mechanisms than arrays.
Let’s take a look at using an ArrayList that contains Strings. A key design goal of the Collections Framework was to provide rich functionality at the level of the main interfaces: List, Set, and Map. In practice, you’ll typically want to instantiate an ArrayList polymorphically like this:
List myFirstArrayList = new ArrayList();
As of Java 5 you’ll want to say
This kind of declaration follows the object oriented programming principle of “coding to an interface”, and it makes use of generics. We’ll say lots more about generics in future, but for now just know that, as of Java 5, the
In many ways, ArrayList
String s = "hi";
There’s lots going on in this small program. Notice that when we declared the ArrayList we didn’t give it a size. Then we were able to ask the ArrayList for its size, we were able to ask it whether it contained specific objects, we removed an object right out from the middle of it, and then we rechecked its size.
Autoboxing with Collections
In general, collections can hold Objects but not primitives. Prior to Java 5, a very common use for the wrapper classes was to provide a way to get a primitive into a collection. Prior to Java 5, you had to wrap a primitive by hand using one of the constructors of that type, before you could put it into a collection. With Java 5, primitives still have to be wrapped, but autoboxing takes care of it for you.
Checkout the Wrapping & Boxing chapter by clicking here (If you want to refresh that topic)
List myFirstIntArray = new ArrayList(); // pre Java 5 declaration
myFirstIntArray.add(new Integer(42)); // had to wrap an int
As of Java 5 we can say
myFirstIntArray.add(42); // autoboxing handles it!
In this last example, we are still adding an Integer object to myFirstIntArray (not an int primitive); it’s just that autoboxing handles the wrapping for us.
Previous Chapter: Chapter 39 - Getting Started with Collections
Next Chapter: Chapter 41 - Sorting Collections & Arrays