jordanpg
jordanpg

Reputation: 6516

In Java, how can I instantiate a generic class with another type variable as the type?

In the Java tutorial, I read that "A type variable [of a generic class] can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable."

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 this, 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 would "another type variable" even mean 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>>();

Upvotes: 3

Views: 174

Answers (3)

dramzy
dramzy

Reputation: 1429

It means if you have another class that uses generics you can set the type to another type variable from that class, so something like this:

public class A<S>{
  private B<S>();

}

public class B<T>{
}

Upvotes: 1

Antoniossss
Antoniossss

Reputation: 32507

I would do something like this

Box <T> extends SomeParametrizedClass<T>{
// class body
private List<T> someList;
}

Here you have parametrized field and superclass with variable types instead of specifically provided types.

Upvotes: 0

Justin
Justin

Reputation: 2031

I think it's referring to a case where it is used inside of another generic class, like this:

class SomeGenericClass<T> {
    Box<T> box = new Box<T>();
}

Where T is another type variable and you could construct the object like this:

SomeGenericClass<Object> someGenericClass = new SomeGenericClass<>();

Where the box initialized in SomeGenericClass is a Box<Object>

It could also be referring to using another generic instance inside your generic class like this:

class Box<T> {
    ArrayList<T> arrayList = new ArrayList<>();
}

And constructing the class like this:

Box<Object> box = new Box<>();

Where the ArrayList inside Box<Object> would be a ArrayList<Object>

Upvotes: 1

Related Questions