Welcome Message

Hi, welcome to my website. This is a place where you can get all the questions, puzzles, algorithms asked in interviews and their solutions. Feel free to contact me if you have any queries / suggestions and please leave your valuable comments.. Thanks for visiting -Pragya.

January 18, 2010

Creating Generic Methods

Imagine you want to create a method that takes an instance of any type, instantiates an ArrayList of that type, and adds the instance to the ArrayList. The class itself doesn't need to be generic; basically we just want a utility method that we can pass a type to and that can use that type to construct a type safe collection. Using a generic method, we can declare the method without a specific type and then get the type information based on the type of the object passed to the method. For example:

import java.uti1.*;
public class CreateAnArrayList {
public < t > void makeArrayList(T t) { // take an object of an
// unknown type and use a
// "T" to represent the type
List< t > list = new ArrayList(); // now we can create the
// list using "T"
list.add(t);
}
}

In the preceding code, if you invoke the makeArrayList() method with a Dog instance, the method will behave as though it looked like this all along:

public void makeArrayList(Dog t) {
List list = new ArrayList();
list.add(t);
}


And of course if you invoke the method with an Integer, then the T is replaced by Integer (not in the bytecode, remember—we're describing how it appears to behave, not how it actually gets it done).

The strangest thing about generic methods is that you must declare the type variable BEFORE the return type of the method:

public void makeArrayList(T t)

The before void simply defines what T is before you use it as a type in the argument. You MUST declare the type like that unless the type is specified for the class. In CreateAnArrayList, the class is not generic, so there's no type parameter placeholder we can use.

You're also free to put boundaries on the type you declare, for example if you want to restrict the makeArrayList() method to only Number or its subtypes (Integer, Float, and so on) you would say

public void makeArrayList(T t)

No comments: