Collection 接口 & ArrayList类
一、API文档中Collection接口的描述
- Collection 层次结构 中的根接口。Collection 表示一组对象,这些对象也称为 collection 的元素。一些 collection 允许有重复的元素,而另一些则不允许。一些 collection 是有序的,而另一些则是无序的。
- 集合的toString方法是重写了的,当打印集合对象的时候,实际上打印的是集合中的元素
二、Collection的成员方法 ①
- boolean add(E e):添加一个元素E(泛型,可以理解成Object)
- boolean remove(Object o):删除一个元素
- void clear():清空集合
- boolean contains(Object o):判断集合是否包含某元素
- boolean isEmpty():判断集合是否为空
- int size():集合中有几个元素
三、ArrayList()
- ArrayList()构造方法:构造一个初始容量为 10 的空列表
- 集合的toString方法是重写了的,当你打印集合对象的时候,实际上打印的是集合中的元素
四、Collection的成员方法①代码实现
package com.collection.demo;
import java.util.ArrayList;
import java.util.Collection;
public class CollectionTest {
@SuppressWarnings("all")
public static void main(String[] args) {
// 创建集合
Collection c = new ArrayList();
//boolean add(E e)
System.out.println(c.add("hello")); // true
c.add("helloworld");
c.add("hellojava");
System.out.println(c); // [hello, helloworld, hellojava]
//boolean remove(Object o)
System.out.println(c.remove("hello")); // true
System.out.println(c.remove("java")); // false
System.out.println(c); // [helloworld, hellojava]
//void clear()
c.clear();
System.out.println(c); // []
//boolean contains(Object o)
System.out.println(c.contains("hello")); // false
//boolean isEmpty()
System.out.println(c.isEmpty()); // true
//int size()
System.out.println(c.size()); // 0
}
}
五、Collection的成员方法 ②
- boolean addAll(Collection c):添加一整个集合
- boolean removeAll(Collection c):删除一整个集合
- boolean containsAll(Collection c):判断是否包含一整个集合的元素
- boolean retainAll(Collection c):求两个集合的交集
六、Collection的成员方法②代码实现
package com.collection.demo;
import java.util.ArrayList;
import java.util.Collection;
public class CollectionTest02 {
@SuppressWarnings("all")
public static void main(String[] args) {
Collection c1 = new ArrayList();
c1.add("hello1");
c1.add("hello2");
c1.add("hello3");
Collection c2 = new ArrayList();
c2.add("hello3");
c2.add("hello4");
c2.add("hello5");
//boolean addAll(Collection c)
//注意:当添加相同的元素时,不会覆盖,依旧可以添加进去
c1.addAll(c2);
System.out.println(c1); // [hello1, hello2, hello3, hello3, hello4, hello5]
//boolean removeAll(Collection c)
c1.removeAll(c2);
System.out.println(c1); // [hello1, hello2]
//boolean containsAll(Collection c)
//注意:包含所有算包含
System.out.println(c1.containsAll(c2)); // false
//boolean retainAll(Collection c)
//注意:该方法是用来求两个集合的交集的,交集操作后的值存在c1中
//在进行交集操作的过程中,如果c1的值发生改变,则返回值为true
System.out.println(c1.retainAll(c2)); // true
System.out.println(c1); // []
System.out.println(c2); // [hello3, hello4, hello5]
}
}