In Java, how can I instantiate a class with a different type variable as type?
In a Java tutorial , I read that "a [generic] type variable can be any non-primitive type that you specify: any class type, any interface type, any array type, or even a variable of a different type ."
In other words, given this:
class Box<T> {
private T t;
public void set(T t) { this.t = t; }
public T get() { return t; }
}
I can do it as written:
Box<Object> box1 = new Box<>();
Box<Serializable> box2 = new Box<>();
Box<Comparable<Object>> box3 = new Box<>();
Box<char[]> box4 = new Box<>();
But what about a type variable? What does "variable of a different type" mean even at compile time?
// nothing like this works
// Box<Z> box5 = new Box<>();
// Box<<Z>> box5 = new Box<>();
// Box<Z> box5 = new Box<Z>();
// Box<<Z>> box5 = new Box<<Z>>();
source to share
I think this refers to the case where it is used inside another generic class, for example:
class SomeGenericClass<T> {
Box<T> box = new Box<T>();
}
Where T
is another type variable and you can construct an object like this:
SomeGenericClass<Object> someGenericClass = new SomeGenericClass<>();
Where box
, initialized in SomeGenericClass
isBox<Object>
It can also refer to using another shared instance inside your shared class like this:
class Box<T> {
ArrayList<T> arrayList = new ArrayList<>();
}
And let's build the class like this:
Box<Object> box = new Box<>();
Where will it be ArrayList
insideBox<Object>
ArrayList<Object>
source to share