3

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>();
}
1
  • 1
    I'd think twice about using a Vector. Have you considered using a List instead? Commented Jun 16, 2012 at 21:17

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Seems like that should be a static method.
1

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.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.