
正文
java 添加一组元素
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
在java包中的Arrays和Collection类中都有很多实用方法,可以在一个Collection中添加一组元素,Array.asList()方法接受一个数组或是一个用逗号分隔的元素列表(使用可变参数),并将其转化为一个List对象,Collections.addAll()方法接受一个Collection对象,以及一个数组或一个逗号分割的列表,将元素添加到Collection中
//: holding/AddingGroups.java
// Adding groups of elements to Collection objects.
package object;
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));//Collection可以接受另一个Collection初始化自己
Integer[] moreInts = { 6, 7, 8, 9, 10 };
collection.addAll(Arrays.asList(moreInts));//collection.addAll运行速度快
// Runs significantly faster, but you can't
// construct a Collection this way:collection.addAll只能接受另一个collection作为参数
Collections.addAll(collection, 11, 12, 13, 14, 15);
Collections.addAll(collection, moreInts);//将moreInts添加进collection
// Produces a list "backed by" an array:
List<Integer> list = Arrays.asList(16, 17, 18, 19, 20);//list底层表示是数组,不能调整数组大小
list.set(1, 99); // OK -- modify an element
//list.add(21); // Runtime error because the
// underlying array cannot be resized.
}
} ///:~
Arrays.asList()方法不能之间向上转型,必须插入一条线索,以告诉编译器队医Arrays.asList()产生的List类型,实际的目标是什么这称为: 显示类型说明参数说明
Map除了用另一个Map之外,Java标准类库没有提供其他任何自动初始化它们的方法
//: holding/AsListInference.java
// Arrays.asList() makes its best guess about type.
package object;
import java.util.*;class Snow {}
class Powder extends Snow {}
class Light extends Powder {}
class Heavy extends Powder {}
class Crusty extends Snow {}
class Slush extends Snow {}public class AsListInference {
public static void main(String[] args) {
List<Snow> snow1 = Arrays.asList(
new Crusty(), new Slush(), new Powder());
// Won't compile:
// List<Snow> snow2 = Arrays.asList(
// new Light(), new Heavy()); //Arrays.asList会创建List<Powder>而不是,,List<Snow>
// Compiler says:
// found : java.util.List<Powder>
// required: java.util.List<Snow> // Collections.addAll() doesn't get confused:
List<Snow> snow3 = new ArrayList<Snow>();
Collections.addAll(snow3, new Light(), new Heavy());
//Collections.addAll 从它的第一个参数中了解到了目标类型是什么
// Give a hint using an
// explicit type argument specification:
List<Snow> snow4 = Arrays.<Snow>asList(
new Light(), new Heavy());
}
} ///:~








