记渣渣踩坑系列 -使用Arrays.asList 将数组array 转为List 踩坑记录

1 篇文章 0 订阅
1 篇文章 0 订阅
/**
 * zhazhahao使用  Arrays.asList:将数组转为List集合引发的思考。
 * 
 * 	问题1、Arrays.asList 方法传入基本类型数组(int[])和包装类型数组(Integer[])
 *            返回数据格式是否都为List<int>或List<Integer>?
 * 
 * 	问题2、返回的集合List 是否是传统意义上的集合:是否做add和remove删除动作
 *  
 * TestZhaZhaAsList 
 * @author shiyuqiong 
 * @date 2018年9月19日 上午10:40:44
 *
 */
public class TestZhaZhaAsList {

	public static void main(String[] args) {
		
		int[] intList={1,2};// eg1:
		System.out.println(JSONObject.toJSONString(Arrays.asList(intList)));// eg2:输出 [[1,2]]
		
		Integer[] integerList={1,2};// eg3:
		System.out.println(JSONObject.toJSONString(Arrays.asList(integerList)));// eg4:输出 [1,2]
		
		
		testIn(intList);//5 输出什么?
		
		testIn(integerList);//6  输出什么?
		
	}
	
	public static <T> void  testIn(T...args){
		
		System.out.println(JSONObject.toJSONString(args));
	}
}
/**
 *   答一:在运行代码时候回发现  标注为2的代码行输出结构为 [[1,2]],
 *        代码4:位置输出为 [1,2],那么为什么int[]基本类型数组转为List会输出
 *        结果为一个二维数组?
 *       看Arrays.asList(T... a) ,发现asList方法参数为 “泛型可变参数类型”,
 *       经编译器编译进行类型擦除后变为: Arrays.asList(Object[] a)。
 *       然而,int[] 不能被转为 Object[]数组类型。 
 *       因为 auto boxing 和 unboxing 是针对 基本类型和其对应的封装类型来讲。
 *       这时候eg2 这个位置, intList 参数会被当成 Object[] 对应中储存的
 *       对象:Arrays.asList(Object[] a) a 变成 int[][],
 *       以至于Arrays.asList返回为 List<int[]> 。
 *       
 *       Integer[] 可转为Object[] 所以此时Arrays.asList(Object[] a) 
 *       a 的实际数据类型了Integer[] 数组类型
 *       
 *   
 *   答二:    对于第二个问题可见文档(
 *       * 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}.
 *   )意思是说:asList返回是一个固定长度的List 。该方法主要是将array转为List   
 *     可使用 collection中对应的api。
 *     且这里Arrays.asList返回ArrayList 其实是java.util.Arrays.ArrayList.ArrayList 
 *     并不是java.util.ArrayList<E> 。
 *     之所以 asList 返回的 集合能够使用collection API。:
 *     java.util.Arrays.ArrayList. ArrayList<E> extends AbstractList<E> 
 *         implements List<E>, RandomAccess, Cloneable, java.io.Serializable
 *                                             
 *    
 *        
 */

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值