Arrays类和Collections的运用

Arrays 和Collections 是为了方便对array 对象,和collection对象进行操作的,他里面的方法都是静态方法


以方便直接接入对象引用

常见的方法有:

Arrays.asList(数组对象)  //此静态方法用于将Array转化为List类型对象。常常用于List类型对象的初始化中。

Collection.addAll(Collection对象,数组对象或可变参数列表 ) //次静态方法用于向一个已经存在的Collection中拼接数据

Collection<String>  appleStore= new ArrayList<String>(Arrays.asList("Sweet,Sour".split(",")));

为了对ArrayList<String>进行初始话,Oracle公司提供了三种重载的构造器:

1、ArrayList() 
          Constructs an empty list with an initial capacity of ten.

2、ArrayList(Collection c) 
          Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.

3、ArrayList(int initialCapacity) 
          Constructs an empty list with the specified initial capacity.

此处使用了第二个构造器,即传入一个List对象。 

此处"Sweet,Sour".split(",")首先将字符串对象转化为了一个String数组,包含两个对象。

而后调用Array.asList(数组对象),将其转换为一个List对象。

!值得注意的是collection对象.addAll(list对象),注意此处是collection对象而非Collections类。

 

Example2:

Collection<String> appleStore=new Collection<String>();

String[] strArray="Sweet0,Sour0".split(",");

Collections.addAll(appleStore, strArray);

Collections.addAll(appleStore, Sweet1, Sour2);

此使用了静态方法Collections.addAll, 可以发现其在初始化上更具有灵活性,第一个参数为Collection对象,第二个可以是一个数组或可变参数列表(实质是数组,只是java编译器的可变参数列表功能,可以实现自动的将其转换为数组)。

 

Collections.addAll()方法和collection.add()在处理过程上具有很大的差别,所以其效率上的差距也很大,适用于不同的场景,以下为国外论坛上的一些经典解释。

Let's take a closer look at the two of them:


col.addAll(Arrays.asList(1,2,3,4,5));   //此处采用collection.addAll()

Here's what happens:

  1. varags + autoboxing creates Integer[]  //可变参数列表,并且采用Integer的自动包装器
  2. Arrays.asList creates a List<Integer> backed by the array  //根据数组生成相应的List
  3. addAll iterates over a Collection<Integer> using Iterator<Integer> //通过迭代器访问并添加每一个对象
// b)
Collections.addAll(col,1,2,3,4,5);   //使用Collections.addAll()静态方法

Here's what happens:

  1. varargs + autoboxing creates Integer[]  //可变参数列表,自动包装器
  2. addAll iterates over an array (instead of an Iterable<Integer>)  //迭代访问数组

We can see now that b) may be faster because:

Arrays.asList call is skipped, i.e. no intermediary List is created.   //采用Collections.addAll()可以不用建立过渡的List对象,而是直接进行遍历添加



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值