简体   繁体   English

具有通用类型变量List的类

[英]class with generic type variable List

I'm reading about generic types. 我正在阅读有关泛型类型的信息。 I'm able to understand that generic types can be used to specify the type of content can be consumed by objects or collections to avoid runtime error and solve it while compile time only. 我能够理解,泛型类型可用于指定对象或集合可以使用的内容类型,以避免运行时错误并仅在编译时解决它。

I want to know how can I create a generic class whose type variable(T = List) is List. 我想知道如何创建其类型变量(T = List)为List的泛型类。 For example in below example its String. 例如,在下面的示例中,它的字符串。

import java.util.ArrayList;
import java.util.List;

public class Test<T> {

    T string;

    public Test(T in) {

        this.string = in;

    }

    public static void main(String args[]) {

        Test<String> o = new Test<String>("Generic");


    }
}

I want to know how can I create a generic class whose type variable(T = List) is List. 我想知道如何创建其类型变量(T = List)为List的泛型类。

Specify the List as parameterized type. List指定为参数化类型。

To have a generic Test of List<String> do for example : 要拥有List<String>的通用测试,例如:

List<String> myList = new ArrayList<>();
...
Test<List<String>> o = new Test<>(myList);

If you want your list strictly to be a list of strings. 如果您希望您的列表严格是字符串列表。 Then simply declare your list as List<String> 然后只需将您的列表声明为List<String>

in this way obliges the developer to use a class that belongs to the Collection es (List, ArrayList, Vector, ...) 通过这种方式,开发人员有义务使用属于Collection es的类(List,ArrayList,Vector等)。

public class Test<T extends Collection>{ ... }

UPDATE 更新

public class Test<E,T extends Collection<E>>{ ... }

Just déclare your T like an extends of List Change this: 只需像声明List的扩展一样声明您的T即可:

public class Test<T> {

to this 对此

public class Test<T extends List> {

In this case, you will not be able to write this: 在这种情况下,您将无法编写以下代码:

Test<String> o = new Test<String>();

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

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