在程序运行之前,往往不知道需要具体创建多少个对象,而我们又通常需要保存这些对象。
虽说数组也可以存储对象,但必须为数组指定固定长度,使得其使用起来存在限制,不够灵活。为了解决这一问题,Java 提供了一整套容器类来解决这个问题,也称为“集合”,其中的基本类型包括:List、Set、Queue 和 Map,每个基本类型还拥有多个导出类,在后续的文章中会依次介绍。
基本类型 | 用途 |
List | 以特定顺序保存一组元素 |
Set | 容器内元素不能重复 |
Queue | 只允许在容器的一“端”插入元素,另一“端”取出元素 |
Map | 每个槽位可保存两个对象,即一组键值对(key和value,通过key取对应的value,类似于小型数据库) |
其中 List、Set、Queue 都实现了 Collection 接口,可以按顺序创建元素序列,Map 则是一组成对的键值对对象,也被称为“关联数组”或“字典”。
首先,我们来看看如何创建一个容器:
public class Apple {
public void getApple() {
System.out.println("get an apple");
}
}
public class Orange {
public void getOrange(){
System.out.println("get an orange");
}
}
public class AppleList {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList<>();
Apple a1 = new Apple();
arrayList.add(a1);
Orange o1 = new Orange();
arrayList.add(o1);
for (Object o : arrayList) {
Apple apple = (Apple) o;
apple.getApple();
}
}
}
get an apple
Exception in thread "main" java.lang.ClassCastException: mtn.baymax.charpter11.Orange cannot be cast to mtn.baymax.charpter11.Apple
at mtn.baymax.charpter11.AppleList.main(AppleList.java:19)
ArrayList 是 List 的一个子集,生成一个 ArrayList 对象,通过 add()方法可以将元素放入到集合中,之后可通过循环遍历集合中的元素。
但上述例子中,存在一个问题,任何类型的对象都可以放入到集合之中,ArrayList 中默认的元素类型为 Object,当你想把它取出来作为 Apple 使用时,需要进行强制转型。
若不慎将非 Apple 对象放入集合中,在尝试强制转型为 Apple 时,便会得到类型参数转换错误的异常,故在生成 List 集合时,往往需要制定集合的泛型。
上述例子需要如下更改:
public class AppleList {
public static void main(String[] args) {
ArrayList<Apple> arrayList = new ArrayList<>();
Apple a1 = new Apple();
arrayList.add(a1);
}
}
当指定泛型后,再往集合中添加元素的时候,会进行类型检查,类型不一致则会产生编译错误。
接下来,我们再来看看如何往集合中添加一组元素:
public class AddingGroups {
public static void main(String[] args) {
Collection<Integer> collection = new ArrayList<>(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);
Collections.addAll(collection, moreInts);
List<Integer> list = Arrays.asList(16, 17, 18, 19, 20);
list.set(1, 99);
//list.add(21);
}
}
ArrayList() 的构造方法支持接收另一个 Collection 对象进行初始化。Arrays.asList() 可将数组转化为 List 对象。
Collection<Integer> collection = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
collection .addAll() 支持将另一个 collection 添加至自身容器中
Integer[] moreInts = {6, 7, 8, 9, 10};
collection.addAll(Arrays.asList(moreInts));
Collections.addAll() 支持将一个数组添加至 collection 中,同时也支持将数组换成可变参数传入。
Collections.addAll(collection, moreInts);
Collections.addAll(collection, 11, 12, 13, 14, 15);
这里需要注意的是通过 Arrays.asList() 转换得到的 List ,底层仍然是数组,不可改变其长度,可通过set() 方法改变对应位置元素的内容,但调用 add()方法会得到 java.lang.UnsupportedOperationException 不支持的操作类型错误。
List<Integer> list = Arrays.asList(16, 17, 18, 19, 20);
list.set(1, 99);
//list.add(21);