How do I create a generic collections?

In this example you will learn how to create a generic collections. Using a generic collections you can define the type of object stored in the collections. Most of the time when you are working with a collection you will store the same kind of object in it. So it is safer to work if you know what to store in the collection and what to expect when try to read some data from it without worried of creating a runtime error in your code because you place a wrong object in the collection.

Using the generic type mechanism introduced since JDK 5.0 you can declare a collections with reference to the given type. You define the type inside an angle brackets after the variable declaration and after the variable instantiation. In JDK 7.0 you can simplify this using the diamond operator. For example is you want to create a collection that stored Customer objects the declaration and instantiation code will look like the snippet below.

List<Customer> customers = new ArrayList<Customer>();

In JDK 7.0 you can write it without repeating the type on the instantiation part.

List<Customer> customers = new ArrayList<>();

Creating a collection object in this way will tell to compiler that you want to allow only to add objects of type Customer to be the content of the collection. It means the add method will take Customer as the argument and the get method will return Customer object. If you are trying to add for example Product object or Seller object the compiler will give you a compiled time error.

Let’s see a complete code snippet for this example:

package org.kodejava.generics;

import org.kodejava.generics.support.Customer;

import java.util.ArrayList;
import java.util.List;

public class GenericCollection {
    public static void main(String[] args) {
        List<Customer> customers = new ArrayList<>();
        customers.add(new Customer());
        customers.add(new Customer());

        //customers.add(new Product()); // Compile time error!

        // No cast operator required.
        Customer customer = customers.get(0);

        for (Customer cust : customers) {
            System.out.println(cust);
        }
    }
}

Another thing that you can see from the code above is that you don’t have to use cast operator anymore when obtaining data from the collection. On JDK prior to 5.0 version you will typically have to use the instanceof operator to see what type of object returned by the collection, and you have to cast it. You don’t have to do this anymore when using generic. You can also see how your code become simpler and more readable when you iterate through the contents of the collection object.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.