集合
1.集合框架概述
-
集合 Collection The Collection in Java is a framework that provides an architecture to store and manipulate the group of objects.
数组同样也是对多个数据进行存储操作的结构(此时的存储指内存层面的此时,不涉及持久化的存储)
-
数组存储的特点
- 长度固定:一旦初始化完毕,其长 度就不可修改
- 数组类型固定:数组定义好后,只能操作指定类型的数据
-
数组存储的弊端
- 长度不可修改:初始化后,同一个数组对象长度不可再修改
- 增删改效率低
- 缺乏属性或方法
- 无法满足无序、不可重复的需求:数组的存储特点是有序、可重复
-
集合的优点
- 动态长度
- 增删改效率高
- 相应属性或方法
- 有无序、不可重复的Set接口,也有有序、可重复的List接口
-
接口继承树
2. Collection接口
2.1 概述
Collection是单列数据,定义了存取一组对象的方法的集合。
Collection接口是List、Set和Queue接口的父接口,在JDK1.5之前,集合会丢掉容器中所有对象的数据类型,在JDK1.5加了泛型之后,集合可以记住容器中所有对象的数据类型。
2.2 方法
-
添加
add(Object obj)
addAll(Collection coll)
-
获取有效元素的个数
int size()
-
清空集合
void clear()
-
是否是空集合
boolean isEmpty()
-
是否包含某个元素
boolean contains(Object obj)
:是通过元素的equals方法来判断是否是同一个对象boolean containsAll(Collection c)
:也是调用元素的equals方法来比较的。比较集合中是否包含c集合中的所有元素 -
删除
boolean remove(Object obj)
:通过元素的equals方法判断是否是要删除的那个元素。只会删除找到的第一个元素boolean removeAll(Collection coll)
:取当前集合的差集 -
取两个集合的交集
boolean retainAll(Collection c)
:把交集的结果存在当前集合中,不影响c -
集合是否相等(注意顺序)
boolean equals(Object obj)
-
转成对象数组
Object[] toArray()
-
获取集合对象的哈希值
hashCode()
-
遍历
iterator()
:返回迭代器对象,用于集合遍历
2.3 集合和数组的转换
-
集合到数组:Collection的
toArray()
方法Collection coll1 = new ArrayList();
coll1.add(123);
coll1.add("abc");
coll1.add(new Person("Tom", 18));
Object[] os = coll1.toArray();
for (Object o : os) {
System.out.println(o);
}
/*Output
123
abc
Person{name='Tom', age=18}
*/ -
数组到集合:Arrays的
asList()
方法Collection coll2 = new ArrayList();
String[] str = new String[]{"AA", "BB", "CC"};
coll2 = Arrays.asList(str);
coll2.forEach(String -> System.out.println(String));
/*Output
AA
BB
CC
*/-
深入Arrays的asList()方法
首先查看asList()方法的源码
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}返回的ArrayList类是Arrays的私有类ArrayList,它同样实现了AbstractList接口
private static class ArrayList<E> extends AbstractList<E>
implements RandomAccess, java.io.Serializable
{
...
private final E[] a;
ArrayList(E[] array) {
a = Objects.requireNonNull(array);
}
....
}可以看到,Arrays中的ArrayList和List接口的ArrayList类是不同的
String[] str = new String[]{"AA", "BB", "CC"};
//此时不再向上转型
ArrayList coll3 = new ArrayList();
coll3 = Arrays.asList(str);//报错
-