Java Articles

Advertisement

Generic Type Example

by Ram Satish

Share

In my previous article, I introduced you to Java Generics. In this article, I will show you how to define a generic type.

Generic Type Example

Class Node below has a type parameter <E>. It is like any regular class but has a type declaration attached between the two angular brackets.

public class Node<V> {
private V mValue;

public Node(V value) {
mValue = value;
}

public V getValue() {
return mValue;
}
}

There can be more than one type parameters between the angular brackets in which case the type parameters need to be comma separated. For example:

Advertisement
public class Node<K, V> {
private K mKey;
private V mValue;
public Node(K key, V value) {
mKey = key;
mValue = value;
}

public V getValue() {
return mValue;
}

public K getKey() {
return mKey;
}
}

How to use the above generic type

Class Node has two type parameter K and V. When we instantiate it, they will be replaced the actual arguments.
In the below test case, I create a Node instance, passing Integer and String as the actual arguments.

	public void testNode() {
Node<Integer, String> n = new Node<Integer, String>(1, "One");
Integer i = n.getKey();
String s = n.getValue();
assertEquals(1, i.intValue());
assertEquals("One", s);
}

What is the scope of the type parameters?

Since we have defined type parameters K and V at class level, they can be used anywhere in the class.
You would have noticed, the type parameters are used in the constructor as arguments.
public Node(K key, V value)

They are used as return types:
public V getValue()
public K getKey()

They are also used as the type of instance variables.
private K mKey;
private V mValue;

What are bounded and Un-bounded types?

Note that in our node example, we didn’t call any methods on the type parameters K and V. This is because at the code level, we have no idea what these types represent.
Since they can represent any type, they are called unbounded. A type can also be bounded.
For example, in the below Node class, I make K extend Number. Now K is bounded. It is a type of Number though the actual type that will replace this formal type is still unknown.
We will now be able to call methods on K. In the constructor, I call key.byteValue() to get its byte value.

public class Node<K extends Number, V> {
private K mKey;
private V mValue;
private byte mByte;
public Node(){}
public Node(K key, V value) {
mKey = key;
mValue = value;
mByte = key.byteValue();
}
...
}
Advertisement

Share

Related

Advertisement

Latest

Advertisement