使用和声明泛型 List<T>

编程入门 行业动态 更新时间:2024-10-27 12:33:17
本文介绍了使用和声明泛型 List<T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

所以我在 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-16 11:41:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/885790.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:声明   List   gt   lt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!