I was confused about how to use generics (generic type), so I wrote an example that I often use.
public class Foo<T> {
T t;
public T get() {
return t;
}
public void set(T t) {
this.t = t;
}
}
When using multiple parameters, separate them with `Foo <T, U>`
and commas.
public class Foo<T extends Parent> {
T t;
public T get() {
return t;
}
public void set(T t) {
this.t = t;
}
}
It is inconvenient when you want to make a temporary decision if you specify it for the entire class. For example, when you want to convert a List to an array
List list = new ArrayList<String>();
list.add("foo1");
list.add("foo2");
list.add("foo3");
String[] strList = list.toArray(new String[list.size()]);
I think you may use the toArray method like this. The implementation at this time
public class Foo {
public <T> T get(T t) {
return t;
}
}
At this time, T is determined by looking at the argument type.
Not surprisingly, it cannot be `new T ()`
. The reason is that there is no guarantee that an instance can be created unless you know who T is.
public class Foo<T extends Parent> {
public T get() {
return new T(); //Can not!!
}
}
It seems that you can create an instance from the Class class using java refactoring to achieve coding like new T ()
, but the performance seems to drop significantly.
Recommended Posts