Java - 一种采用 vararg 并返回 arraylist 的方法? [英] Java - A method that takes vararg and returns arraylist?

查看:25
本文介绍了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));
}

请注意,您可以查看 Arrays.asList 已声明,因为从类型的角度来看,它的作用大致相同.

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天全站免登陆