J2SE 5.0 introduces many new collections api-you need to understand them so that you can properly implement a generic custom collection-it can seamlessly work with multiple types and new "for each" structures. This article shows you how to create a collection that is compatible with the latest features of J2SE.
First, create a class that supports generics
First, you must learn how to create a class that allows for a "generic type". This means that whenever you instantiate your class, you can specify one or more Java types to associate with the class. To illustrate this issue, consider a simple example class in Listing 1.
Notice how the class in Listing 1 is declared. It specifies three generics between the angle brackets. These generics are placeholders for real types. When you declare a class of this type, you can specify a class to replace One,two and three. If you do not, then the class will use the default type of object.
This class shows how to design a class to receive three generic types. When you create a class of this type, you want to support the exact type.
List 1. Generic class:
package com.heatonresearch.examples.collections;
public class Example<ONE, TWO, THREE> {
private ONE one;
private TWO two;
private THREE three;
public ONE getOne() { return one; }
public void setOne(ONE one) { this.one = one; }
public THREE getThree() { return three; }
public void setThree(THREE three) { this.three = three; }
public TWO getTwo() { return two; }
public void setTwo(TWO two) { this.two = two; }
public static void main(String args[]) {
Example<Double, Integer, String> example = new
Example<Double, Integer, String>();
example.setOne(1.5);
example.setTwo(2);
example.setThree("Three");
}
}
Here's how to instantiate a class with a example type:
Example example=new Example();
The preceding code replaces the specific Double,integer and string types-equivalent to the "one", "two", and "THREE" placeholders in Listing 1. You can see that these variables all have these types, and set their values by three lines below.
example.setOne(1.5);
example.setTwo(2);
example.setThree("Three");
Now that you know how to create a custom class that uses generics, it's simpler to create a custom collection class that uses generics.