Arrays.asList(T []数组)? [英] Arrays.asList(T[] array)?

查看:172
本文介绍了Arrays.asList(T []数组)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此​​,有<一个href=\"http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#asList%28T...%29\"><$c$c>Arrays.asList(T... A) 但这个工程的可变参数。

如果我已经有一个 T []一个数组?有没有一种方便的方法来创建一个列表&LT; T&GT; 离开这里,或做我必须做手工为:

 静态公网&LT; T&GT;清单&LT; T&GT; arrayAsList(T []一)
{
   清单&LT; T&GT;结果=新的ArrayList&LT; T&GT;(则为a.length);
   为(T T:一)
     result.add(T);
   返回结果;
}


解决方案

只是因为它具有可变参数的工作原理并不意味着你不能正常调用它:

 的String [] X = {A,B,C};
清单&LT;串GT;清单= Arrays.asList(X);

唯一棘手位是,如果 T 对象,你应该使用一个投来告诉编译器是否它应该换参数在数组或不:

  [对象]×= ...;
清单&LT;对象&gt;清单= Arrays.asList((对象[])x)的;

  [对象]×= ...;
清单&LT;对象[]&GT;清单= Arrays.asList((对象)x)的;

So there's Arrays.asList(T... a) but this works on varargs.

What if I already have the array in a T[] a? Is there a convenience method to create a List<T> out of this, or do I have to do it manually as:

static public <T> List<T> arrayAsList(T[] a)
{
   List<T> result = new ArrayList<T>(a.length);
   for (T t : a)
     result.add(t);
   return result;
}

解决方案

Just because it works with varargs doesn't mean you can't call it normally:

String[] x = { "a", "b", "c" };
List<String> list = Arrays.asList(x);

The only tricky bit is if T is Object, where you should use a cast to tell the compiler whether it should wrap the argument in an array or not:

Object[] x = ...;
List<Object> list = Arrays.asList((Object[]) x);

or

Object[] x = ...;
List<Object[]> list = Arrays.asList((Object) x);

这篇关于Arrays.asList(T []数组)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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