一、Collection 集合
1.1、Collection 集合概述和使用
1.1.1、Collection 集合概述
- 是单例集合的顶层接口,它表示一组对象,这些对象也称为 Collection 的元素。
- JDK 不提供此接口的任何直接实现,它提供更具体的子接口(如 Set 和 List)实现。
1.1.2、使用 Collection 集合
// 创建 Collection 集合对象
Collection<String> c = new ArrayList<>();
// 添加元素
c.add("hello");
c.add("world");
c.add("java");
// 输出结果
System.out.println(c);
1.2、Collection 集合常用方法
| 方法名 |
说明 |
| boolean add(E e) |
添加元素 |
| boolean remove(Object o) |
从集合中移除指定的元素 |
| void clear() |
清空集合中的元素 |
| boolean contains(Object o) |
判断集合中是否存在指定的元素 |
| boolean isEmpty() |
判断集合是否为空 |
| int size() |
集合的长度,也就是集合中元素的个数 |
1.2.1、add(E e) 方法
// 创建 Collection 集合对象
Collection<String> c = new ArrayList<>();
// 添加元素
c.add("hello");
c.add("world");
c.add("java");
// 输出结果
System.out.println(c);
1.2.2、remove(Object o) 方法
- 从集合中移除指定的元素,删除成功返回 true,失败返回 false。
// 创建 Collection 集合对象
Collection<String> c = new ArrayList<>();
// 添加元素
c.add("hello");
c.add("world");
c.add("java");
// 删除元素
System.out.println(c.remove("a"));
System.out.println(c.remove("hello"));
// 输出结果
System.out.println(c);
1.2.3、clear() 方法
// 创建 Collection 集合对象
Collection<String> c = new ArrayList<>();
// 添加元素
c.add("hello");
c.add("world");
c.add("java");
// 清空集合
c.clear();
// 输出结果
System.out.println(c);
1.2.4、contains(Object o) 方法
// 创建 Collection 集合对象
Collection<String> c = new ArrayList<>();
// 添加元素
c.add("hello");
c.add("world");
c.add("java");
// 判断集合中是否有指定元素
System.out.println(c.contains("12")); // false
System.out.println(c.contains("hello")); // true
// 输出结果
System.out.println(c);
1.2.5、isEmpty() 方法
// 创建 Collection 集合对象
Collection<String> c = new ArrayList<>();
// 添加元素
c.add("hello");
c.add("world");
c.add("java");
System.out.println(c.isEmpty());
c.clear();
System.out.println(c.isEmpty());
// 输出结果
System.out.println(c);
1.2.6、size() 方法
// 创建 Collection 集合对象
Collection<String> c = new ArrayList<>();
// 添加元素
c.add("hello");
c.add("world");
c.add("java");
System.out.println(c.size());
1.3、Collection 集合的遍历
- iterator:迭代器,集合的专用遍历方式。
- Iterator<E> iterator():返回此集合中元素的迭代器,通过集合的 iterator() 方法得到
- 迭代器是通过集合的 iterator() 方法得到的,所以我们说它是依赖于集合而存在的
1.3.1、Iterator 常用方法
| 方法名 |
说明 |
| E next() |
返回迭代中的下一个元素 |
| boolean hasNext() |
如果迭代具有更多元素,则返回 true |
1.3.1.1、next() 方法
// 创建 Collection 集合对象
Collection<String> c = new ArrayList<>();
// 添加元素
c.add("hello");
// 回此集合中元素的迭代器,通过集合的 iterator() 方法得到
Iterator<String> it = c.iterator();
System.out.println(it.next());
1.3.1.2、hasNext() 方法
// 创建 Collection 集合对象
Collection<String> c = new ArrayList<>();
// 添加元素
c.add("hello");
c.add("world");
c.add("java");
Iterator<String> it = c.iterator();
while (it.hasNext()){
String s = it.next();
System.out.println(s);
}