Basic Introduction to Collections


You'll be covering Collections in detail next year so this article is only going to provide a brief introduction. A Collection is like an enhanced Array. It is designed to store collections of objects(no primitives allowed) at runtime. The main reason a Collection is far better than an Array for storing objects is the fact that you don't need to specify and upper bound index! This means you can easily create a Collection and keep adding objects to it at your hearts content.


For this article, we will be demonstrating the use of an ArrayList. An ArrayList is a type of Collection (it inherits from Collection), there are a few other types but we will not get into that in this article.

Creating and filling an ArrayList

The following code will declare an ArrayList of Students. You will need to add some imports for this, but Netbeans will take care of that for you:

ArrayList<Student> students = new ArrayList<Student>();

In the above code snippet, "Student" can be replaced by any type of object you wish (e.g. String, User, Driver, etc). Putting "Student" in the angled brackets is called Generics, and will not be explained in detail in this article. Lets just summarise by saying that the Generic ensures that the ArrayList contains Students and only Students, adding any other type will cause an error.

Adding objects to an ArrayList:

//Declare an ArrayList to hold Students

ArrayList<Student> students = new ArrayList<Student>();

//Declare some Student objects
Student student1 = new Student("Bryan Jones");
Student student2 = new Student("Bryan Smith");
Student student3 = new Student("Bryan Browne");

//Add the Students to the ArrayList

Now that the ArrayList is filled with some objects, we have a lot of ArrayList methods available to use:

//Get the current size of the ArrayList (Similar to Array.length)

//Getting an object out of the ArrayList by index
Student student = students.get(2);

//Looping through the ArrayList (Using a foreach loop in Java)
for(Student student : students){ //This line is equivalent to saying "for each Student in students"