Java-是否需要vararg并返回arraylist的方法? [英] Java - A method that takes vararg and returns arraylist?

查看:76
本文介绍了Java-是否需要vararg并返回arraylist的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对泛型不完全满意,因此尚未找到解决方案.我有以下三种方法:

I'm not entirely comfortable with generics and thus haven't found a solution to this yet. I have these three methods:

public static List<ObjectA> objectAAsList(ObjectA ... items) {
    return new ArrayList<>(Arrays.asList(items));
}

public static List<ObjectB> objectBAsList(ObjectB ... items) {
    return new ArrayList<>(Arrays.asList(items));
}

public static List<ObjectC> objectCAsList(ObjectC ... items) {
    return new ArrayList<>(Arrays.asList(items));
}

我如何创建一个采用T(或其他形式)的变量,并为其创建ArrayList的方法?

How can I create a single method that takes a vararg of T (or something) and creates an ArrayList of it?

推荐答案

只需将您的类型替换为类型变量:

Just replace your type with a type variable:

public static <T> List<T> genericAsList(T ... items) {
    return new ArrayList<>(Arrays.asList(items));
}

请注意,您可以查看

Note that you could look at how Arrays.asList is declared, since it does largely the same thing, from a type perspective.

这篇关于Java-是否需要vararg并返回arraylist的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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