看项目源码,发现不懂的地方:
/** * Returns a fixed-size list backed by the specified array. (Changes to * the returned list "write through" to the array.) This method acts * as bridge between array-based and collection-based APIs, in * combination with {@link Collection#toArray}. The returned list is * serializable and implements {@link RandomAccess}. * * <p>This method also provides a convenient way to create a fixed-size * list initialized to contain several elements: * <pre> * List<String> stooges = Arrays.asList("Larry", "Moe", "Curly"); * </pre> * * @param a the array by which the list will be backed * @return a list view of the specified array */ @SafeVarargs public static <T> List<T> asList(T... a) { return new ArrayList<>(a); }
后面问了度娘才知道:这是数组转列表的方法。基础啊~~
解释:
1、这是一个静态方法:传入一个数组,返回一个列表;
2、<T>表示泛型,即传入的可以是装着基本类型的元素,也可以是装包装类型或者其他类型对象的元素;
实例:
package test5; import java.util.Arrays; public class test4 { public static void main(String[] args){ String[] a = {"aaaaaa","bbbbbb"}; int[] b = {1,1,1,1}; byte[] c = {1,2,3,4,5}; float[] d = {1.1f,2.1f,3.2f,4.5f}; A[] e = {new A(1),new A(2),new A(3)}; String f1 = "aaaaaa"; String f2 = "bbbbbb"; String[] f = {f1,f2}; System.out.println("a: "+Arrays.asList(a)); System.out.println("b: "+Arrays.asList(b)); System.out.println("c: "+Arrays.asList(c)); System.out.println("d: "+Arrays.asList(d)); System.out.println("e: "+Arrays.asList(e)); System.out.println("f: "+Arrays.asList(f)); } } class A{ private int a; public A(int a) { super(); this.a = a; } }
输出:
a: [aaaaaa, bbbbbb] b: [[I@30de3c87] c: [[B@4e57dc21] d: [[F@6a3522b5] e: [test5.A@4679cf8c, test5.A@67291479, test5.A@39ff48d8] f: [aaaaaa, bbbbbb]
解释:
扫描二维码关注公众号,回复:
994361 查看本文章
【1】通过结果可以看到:基本数据类型打印的都是地址值,而String类型的数组输出的是数组中的元素,这是为啥嘞?通过引用Arrays.asList(T...a)方法,可以知道括号中需要一个含数据类型的实参(T一般就是泛型的意思),而基本数据类型是没有类型的(有点绕,非要用的话可以借助他们的包装类);可是为什么不满足类型还能使用嘞?因为数组也是一个类型(下面的方法是没问题的);也就是说基本数据类型转集合遍历是需要借助其他方法滴,大家可以google或者度娘。
【2】所以,该方法不适用于基本数据类型(byte,short,int,long,float,double,boolean),
该方法将数组与列表链接起来,当更新其中之一时,另一个自动更新;
不支持add和remove方法