简体   繁体   English

在Java中,如何使用另一个类型变量作为类型实例化泛型类?

[英]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 ." Java教程中 ,我读到“一个类型变量[泛型类]”可以是您指定的任何非基本类型:任何类类型,任何接口类型,任何数组类型,甚至是另一个类型变量 。“

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>>();

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: 其中T是另一个类型变量,您可以像这样构造对象:

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

Where the box initialized in SomeGenericClass is a Box<Object> SomeGenericClass box初始化的boxBox<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> ArrayListBox<Object>将是一个ArrayList<Object>

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>{
}

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. 在这里,您可以使用变量类型而不是特定类型的参数化字段和超类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM