In asList using java () method

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/rocling/article/details/102768442

One hundred financial Yunchuang written:

We all know that this method is converted into an array list, it is a static method in the JDK java.util package Arrays class. We must pay attention (see the code and the comments, one can understand a) the use of:

		String s[]={"aa","bb","cc"};
		List<String> sList=Arrays.asList(s);
		for(String str:sList){//能遍历出各个元素
			System.out.println(str);
		}
		System.out.println(sList.size());//为3
		
		System.out.println("- - - - - - - - - - -");
		
		int i[]={11,22,33};
		List intList=Arrays.asList(i);	//intList中就有一个Integer数组类型的对象,整个数组作为一个元素存进去的
		for(Object o:intList){//就一个元素
			System.out.println(o.toString());
		}
		
		System.out.println("- - - - - - - - - - -");
		
		Integer ob[]={11,22,33};
		List<Integer> objList=Arrays.asList(ob);	//数组里的每一个元素都是作为list中的一个元素
		for(int a:objList){
			System.out.println(a);
		}
		
		System.out.println("- - - - - - - - - - -");
		
		//objList.remove(0);//asList()返回的是arrays中私有的终极ArrayList类型,它有set,get,contains方法,但没有增加和删除元素的方法,所以大小固定,会报错
		//objList.add(0);//由于asList返回的list的实现类中无add方法,所以会报错

operation result:

aa
bb
cc
3
- - - - - - - - - - -
[I@287efdd8
- - - - - - - - - - -
11
22
33
- - - - - - - - - - -

The reason why the above reasons, asList look at the source code to understand:

public static <T> List<T> asList(T... a) {
	return new ArrayList<T>(a);
}
private final E[] a;
 
	ArrayList(E[] array) {
            if (array==null)
                throw new NullPointerException();
	    a = array;
	}

If you want to get a new list from the array normal, of course, can be added one by one cycle, you may also have the following two methods:

ArrayList<Integer> copyArrays=new ArrayList<Integer>(Arrays.asList(ob));//这样就                                                           是得到一个新的list,可对其进行add,remove了
copyArrays.add(222);//正常,不会报错
		
Collections.addAll(new ArrayList<Integer>(5), ob);//或者新建一个空的list,把要转换的                                                                   数组用Collections.addAll添加进去

If you want to direct the array as the basic type int [], long [] with asList go directly into the List, then we can choose apache commons-lang toolkit array tools ArrayUtils class toObject () method, is very easy ,as follows:

Arrays.asList(ArrayUtils.toObject(i));//上边的代码:int i[]={11,22,33};,达到了我们想要的效果

This class is very powerful:

 

 

Guess you like

Origin blog.csdn.net/rocling/article/details/102768442
Recommended