使用和声明泛型 List<T> [英] Using and declaring generic List&lt;T&gt;

查看:43
本文介绍了使用和声明泛型 List<T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在 Java 中工作,我想声明一个通用列表.

So I'm working in Java and I want to declare a generic List.

所以到目前为止我正在做的是 Listlist = new ArrayList();

So what I'm doing so far is List<T> list = new ArrayList<T>();

但现在我想添加一个元素.我怎么做?通用元素是什么样的?

But now I want to add in an element. How do I do that? What does a generic element look like?

我试过做一些类似 List.add("x") 的事情,看看我是否可以添加一个字符串,但这不起作用.

I've tried doing something like List.add("x") to see if I can add a string but that doesn't work.

(我不声明 List 的原因是我必须将此 List 传递给另一个仅将 List 作为论证.

(The reason I'm not declaring a List<String> is because I have to pass this List into another function that only takes List<T> as an argument.

推荐答案

你应该有一个泛型类或一个泛型方法,如下所示:

You should either have a generic class or a generic method like below:

public class Test<T>  {
    List<T> list = new ArrayList<T>();
    public Test(){

    }
    public void populate(T t){
        list.add(t);
    }
    public static  void main(String[] args) {
        new Test<String>().populate("abc");
    }
}

这篇关于使用和声明泛型 List<T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆