体系结构:单列集合的顶层接口
因此,Collection中定义的所有方法,其子类均可以使用。
使用方法
| 方法名称 | 说明 |
|---|---|
| boolean add(E e) | 将指定对象添加到集合中 |
| void clear() | 清空集合中的所有元素 |
| boolean remove(E e) | 删除集合中指定的元素 |
| boolean contains(Object obj) | 判断集合中是否含有指定的元素 |
| boolean isEmpty() | 判断集合是否为空 |
| int size() | 返回集合中元素的个数 |
注意:contains方法中如果传入的是一个自己定义的实体类对象的话,需要重写equals方法
遍历方法
迭代器遍历
public void test(){
Collection<String> list = new ArrayList<>();
list.add("hello");
list.add("world");
// 创建迭代器对象
Iterator<String> it = list.iterator();
// 如果当前位置有元素,那么进入循环
while (it.hasNext()) {
String s = it.next(); // 先拿到当前的元素,然后指针向后移动一次
if ("world".equals(s)) {
it.remove();
}
}
System.out.println(list); // [hello]
}
注意:
- 如果当前位置已经没有元素的时候,还调用next方法,会出现NoSuchElementException
- 迭代器遍历完后,指针不会复位
- 循环中只能使用一次next方法(在上面的例子中,即使调用2次,也不会出现异常,因为没有元素的时候,没有再调用next方法)
- 在循环中,如果想删除指定的元素,不能使用Collection的remove方法,而要使用迭代器的remove方法(不能再循环中增加元素)
增强for遍历
所有的单列集合和数组才能用增强for进行遍历
格式:for (元素类型 变量名: 数组或集合) {}
public void test(){
Collection<String> list = new ArrayList<>();
list.add("hello");
list.add("world");
// 这里的s是一个第三方变量,表示循环时集合中的每一个元素,在这里修改s的值,并不会修改原来集合中的元素
for (String s : list) {
System.out.println(s);
s = "qqq";
}
System.out.println(list); // [hello, world]
}
idea有个快捷方法可以快速书写增强for语句:集合.for
lambda表达式遍历
因此,forEach方法中的参数是一个Consumer,而Consumer又是一个函数式的接口(@FunctionalInterface),因此可以使用lambda进行简化。
public void test(){
Collection<String> list = new ArrayList<>();
list.add("hello");
list.add("world");
// 这里的s是集合中的每一个元素
list.forEach(s -> {
System.out.println(s);
});
System.out.println(list); // [hello, world]
}
遍历方式的选择
- 如果在遍历时想删除元素的,请试一下迭代器
- 如果只是遍历的,那么使用lambda或增强for