Anish
Anish

Reputation: 255

writing generic function in java

I want to write a function which would return me a Vector of the specified type which I pass to it. For example:

// Here getNewVector(<ClassType>) should return me an integer Vector.
Vector<Integer> myIntVector = getNewVector(Integer.class);
//should get a String vector in this case and so on.
Vector<String> myStringVector = getNewVector(String.class) ; 

I want to implement getVector(Class classType) in such a way so as to return a new vector of that particular class type. How can we achieve it without using reflections and by not passing the class name as a String(I would like to pass the class type only as I had mentioned in the example above.)

Actually, I want a function getVector() somewhat like this..

Vector<T> getVector(T t) {
    return new Vector<t>();
}

Upvotes: 3

Views: 291

Answers (3)

Louis Wasserman
Louis Wasserman

Reputation: 198211

Why even bother writing a function here?

Vector<Integer> myIntVector = new Vector<Integer>();

or, even better, if you're on Java 7,

Vector<Integer> myIntVector = new Vector<>();

(There's no actual difference at runtime, of course, between vector types with different element types.)

Upvotes: 1

Tim Pote
Tim Pote

Reputation: 28049

Take a look at the Java Tutorial for Generic Methods. Here's one way to do what you want:

public static <T> Vector<T> getVector(Class<T> clazz) {
  return new Vector<T>()
}

public static <T> Vector<T> getVector(T t) {
  Vector<T> vector = new Vector<T>();
  vector.add(t);
  return vector;
}

I'm assuming that you're not going to just want to throw away the t you pass into getVector(T t), so I stuck it in the Vector.

Theoretically, you don't need to pass anything into the method if all you want is the typing mechanism:

public static <T> Vector<T> getVector() {
  return new Vector<T>();
}

//Usage
Vector<Integer> vector = getVector();

Java can figure out that you want it typed as a Vector<Integer> from the generic typing on the declaration.

Upvotes: 8

Martin Matula
Martin Matula

Reputation: 7989

public <T> Vector<T> getNewVector(Class<T> type) {
    return new Vector<T>();
}

Upvotes: 1

Related Questions