Reputation: 1249
Let's say I have something like:
public void do(DataType type) {
ArrayList<DataType> list = new ArrayList<DataType>();
doStuff();
}
In some cases I want to create an arrayList of another type by passing the type as a parameter, how can I do this in Java?
Upvotes: 2
Views: 715
Reputation: 1381
Are you looking for something like this?
public static <T> List<T> doSomething(Class<T> clazz){
ArrayList<T> testList = new ArrayList<T>();
return testList;
// more code
}
and you can invoke this like :
List<Integer> intList = doSomething(Integer.class);
intList.add(1);
List<String> stringList = doSomething(String.class);
stringList.add("test");
and if you want to restrict the type of Class you need, you could use T extends youDataType. If what @subhash has explained is not the one you are looking for, and if what @zoyd explains is true, then i believe this could be of some use.
Upvotes: 1
Reputation: 3559
Java doesn't allow to pass class types as method parameters. As far as I know, the closest you can get is this :
import java.util.*;
class MyClass<T> {
public void stuff() {
ArrayList<T> list = new ArrayList<T>();
//doStuff();
}
}
class Test {
public static void main(String args[]) {
(new MyClass<String>()).stuff();
(new MyClass<Integer>()).stuff();
}
}
So you would need to instanciate the class each time you need it.
Upvotes: 1
Reputation: 2830
More universal approach is the following:
public <T extends IDataType> void doSomething(T type) {
ArrayList<T> list = new ArrayList<T>();
doStuff();
}
where: DataType
implements IDataType
In this case you can use any type which implements IDataType
Upvotes: 1
Reputation: 1738
I assume you want something like this:
public static <T>List<T> makeList(T t) {
List<T> list = new ArrayList<T>();
// doStuff();
return list;
}
And usage of makeList
function:
makeList("String list").add("new String"); // ok
makeList("String list").add(5); // compile error
Upvotes: 1
Reputation: 3140
try this..
public <T> void stuff(T type){
ArrayList<T> arrayList = new ArrayList<T>();
doStuff();
}
generics may be helpfull you if you want to create sigle object that represent it, but when you want a simple private attribute the easy way is this.
Upvotes: 6