持有对象:添加一组元素



/*
 *  2018年3月27日09:30:50
 *  代码目的:显示向容器中批量添加一组元素的方法。
 *  代码位置:P220
 *  Collection<Integer> collection =
      new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5));
      这种方式也是最常用的。
     
      结论:
          Collections.addAll方法运行起来快。
          因此先构建一个不包含元素的Collection,然后调用
          Collections.addAll()这种方式很方便,因此是首选方式。
 * */

//: holding/AddingGroups.java
// Adding groups of elements to Collection objects.
import java.util.*;

public class AddingGroups {
  public static void main(String[] args) {
    Collection<Integer> collection =
      new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5));
    Integer[] moreInts = { 6, 7, 8, 9, 10 };
    //直接通过容器collection的操作,添加元素,addAll方法的参数
    //是一个容器
    collection.addAll(Arrays.asList(moreInts));
    System.out.println(collection);
    // Runs significantly faster, but you can't
    // construct a Collection this way:
    //通过辅助类Collections.addAll向容器collection批量添加元素
    Collections.addAll(collection, 11, 12, 13, 14, 15);
    System.out.println(collection);
    Collections.addAll(collection, moreInts);
    // Produces a list "backed by" an array:
    //注意:Arrays.asList会生成一个固定长度的链表list,可以通过set函数修改某个索引位置的值
    //但如果尝试add或者remove会报错 java.lang.UnsupportedOperationException
    List<Integer> list = Arrays.asList(16, 17, 18, 19, 20);
    System.out.println(list);
    list.set(1, 99); // OK -- modify an element
    System.out.println(list);
    //list.add(21); // Runtime error because the
                     // underlying array cannot be resized.
    Collection<Integer> ii = new ArrayList<Integer>();
    ii.addAll(Arrays.asList(16, 17, 18, 19, 20));
    collection.addAll(ii);
    System.out.println(collection);
    
  }
} ///:~

/*
 *  --------------------------------
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
[16, 17, 18, 19, 20]
[16, 99, 18, 19, 20]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 6, 7, 8, 9, 10, 16, 17, 18, 19, 20]
 *  --------------------------------
 * */


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值