1.集合类体系结构
集合
- 单列集合:Collection
- 可重复:List
- ArrayList
- LinkedList
- Vector
- Stack
- 不可重复:Set
- HashSet
- TreeSet
- LinkedSet
- 可重复:List
- 双列集合:Map
- HashMap
- HashTable
- WeakHashMap
2.Collection集合概述和使用
Collection集合概述
- 是单例集合的顶层接口,它表示一组对象,这些对象也称为Collection的元素
- JDK不提供此接口的任何直接实现,它提供更具体的子接口(如Set和List)实现
创建Collection集合的对象
- 多态的方式
- 具体的实现类ArrayList
package com.study_01;import java.util.ArrayList;import java.util.Collection;public class CollectionDemo01 {public static void main(String[] args) {// 创建Collection集合对象 多态Collection<String> c = new ArrayList<String>();// 添加元素:boolean add(E e)c.add("helllo");c.add("world");c.add("java");// 输出对象System.out.println(c); // [helllo, world, java]}}
3.Collection集合常用方法
| 方法名 | 说明 |
|---|---|
| boolean add(E e) | 添加元素 |
| boolean remove(Object o) | 从集合中移除指定的元素 |
| void clear() | 清空集合中的元素 |
| boolean contains(Object o) | 判断集合中是否存在指定的元素 |
| boolean isEmpty() | 判断集合是否为空 |
| int size() | 集合的长度 |
package com.study_01;import java.util.ArrayList;import java.util.Collection;public class CollectionDemo02 {public static void main(String[] args) {// 通过多态的方法创建对象Collection<String> c = new ArrayList<>();// add方法永远返回true// System.out.println(c.add("hello")); // true// System.out.println(c.add("hello"));// System.out.println(c.add("world"));c.add("hello");c.add("java");c.add("world");// 删除元素:boolean remove(Object o)// System.out.println(c.remove("world")); // true// System.out.println(c.remove("javaee")); // false// 清除集合中的元素:void clear()// c.clear();// 判断集合中是否存在指定的元素:boolean contains(Object o)// System.out.println(c.contains("world")); // true// System.out.println(c.contains("javaee")); // falseSystem.out.println(c.isEmpty()); // 判断集合是否为空System.out.println(c.size()); // 集合的长度System.out.println(c);}}
4.Collection集合的遍历
lterator:迭代器,集合的专用遍历方式
- Iterator iterator:返回此集合中元素的迭代器,通过集合的iterator()方法得到
- 迭代器是通过集合的iterator()方法得到的,所以我们说它是依赖于集合而存在的
lterator中的常用方法
- E next():返回迭代中的下一个元素
- boolean hasNext():如果迭代具有更多元素,则返回true
package com.study_02;import java.util.ArrayList;import java.util.Collection;import java.util.Iterator;public class IteratorDemo {public static void main(String[] args) {// 创建Collection集合对象 多态Collection<String> c = new ArrayList<>();// 添加元素:boolean add(E e)c.add("hello");c.add("world");c.add("java");// Iterator<E> iterator() 返回此集合中元素的迭代器 通过集合的iterator()方法得到Iterator<String> it = c.iterator();/* ----Iterator<E> iterator()-----public Iterator<E> iterator() {return new Itr();}private class Itr implements Iterator<E> {...}*/// 用while循环改进判断// boolean hasNext():如果迭代具有更多元素,则返回truewhile (it.hasNext()) {// E next():返回迭代中的下一个元素String s = it.next();System.out.println( s);}}}
