欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Thinking in Java 11.3 添加一组元素

程序员文章站 2022-05-07 10:49:49
...

功能:
过程:

  • 类AddingGroups

    1、初始化构造使用Arrays.asList方法添加
    2、addAll方法
    3、Collections.addAll方法(首推)
    4、初始化使用Arrays.asList方法添加
    5、更改元素
    个人实现:

package thinking;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class AddingGroups {

	public static void main(String[] args) {
		//Collection<Integer> collection = new Collection<Integer>(Arrays.asList(1,2,3,4,5,6));
		Collection<Integer> collection = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5));
		System.out.println(collection);
		//collection.addAll(6,7,8,9,10);//失败
		collection.addAll(collection);
		System.out.println(collection);
		Collections.addAll(collection, 6,7,8,9,10);
		System.out.println(collection);
		//Collections.addAll(collection, collection);//失败
		List<Integer> list = Arrays.asList(11,12,13,14,15);//未写出,List勿引用错误
		System.out.println(list);
		list.set(0, 1);
		System.out.println(list);

	}

}

原书实现:

package thinkingjava;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

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(Arrays.asList(moreInts));
		Collections.addAll(collection, 11,12,13,14,15);
		collection.addAll(Arrays.asList(moreInts));
		List<Integer> list = Arrays.asList(16,17,18,19,20);
		list.set(1, 99);

	}

}

比较: