Java集合概览

182 阅读2分钟

数组和集合区别

数组

  1. 长度开始时必须指定,而且一旦指定,不能修改;
  2. 保存的必须为同一类型的元素;
  3. 使用数组进行增加/删除元素比较麻烦;

集合

  1. 可以动态保存任意多个对象,使用比较方便;
  2. 提供了一系列方便操作对象的方法: add、remove、set、get;
  3. 使用集合添加,删除新元素的代码简洁明了;

集合的框架体系

Collection体系图

image-20211031124240386

Map体系图

image-20211031124608989

Collection

package java.util;
public interface Collection<E> extends Iterable<E>

实现类的特点

  • Collection实现子类可以存放多个元素,每个元素可以是Object;
  • 有些Collection的实现类,可以存放重复的元素,有些不可以;
  • 有些Collection的实现类,有些是有序的(List),有些不是有序的(Set);
  • Collection接口没有直接的实现子类,是通过它的子接口Set和List来实现的;

接口常用方法

boolean add(E e);  // 添加元素
boolean remove(Object o);  // 删除元素
boolean contains(Object o);  // 查找元素是否存在
int size(); // 获取元素个数
boolean isEmpty();  // 判断是否为空
void clear();  // 清空
boolean addAll(Collection<? extends E> c);  // 添加多个元素
boolean containsAll(Collection<?> c);  // 查找多个元素是否都存在
boolean removeAll(Collection<?> c);  // 删除多个元素

Iterator(迭代器)

Collection继承了Iterable

image-20211031125917488

基本介绍

  • Iterator对象称为迭代器,主要用于遍历Collection集合中的元素;
  • 所有实现了Collection接口的集合类都有一个iterator()方法,用以返回一个实现了Iterator接口的对象,即可以返回一个迭代器;
  • Iterator仅用于遍历集合,Iterator本身并不存放对象。

接口常用方法

boolean hasNext();  // 如果迭代具有更多元素,则返回 true
E next();  // 返回迭代中的下一个元素

注意:在调用it.next()方法之前必须调用it.hasNext()进行检测。若不调用,且下一条记录无效,直接调用it.next会抛出 NoSuchElementException异常。

使用示例

Collection coll = new ArrayList();
coll.add("测试");
// 得到一个集合的迭代器
Iterator iterator = coll.iterator();
// hasNext():判断是否还有下一个元素
while (iterator.hasNext()) {
    // next(): 返回迭代中的下一个元素
    System.out.println(iterator.next());
}

Map

package java.util;
public interface Map<K,V>

实现类的特点(JDK8)

  • Map与Collection并列存在。用于保存具有映射关系的数据:Key-Value;
  • Map中Key和Value可以是任何引用类型的数据,会封装到HashMap$Node对象中;
  • Map中的Key不允许重复,Value可以重复;

接口常用方法

V put(K key, V value);  // 添加
V remove(Object key);  // 根据键删除
V get(Object key);  // 根据键获取
int size();  // 获取元素的个数
boolean isEmpty();  // 判断容器是否为空
void clear();  // 清楚
boolean containsKey(Object key);  // 查找键是否存在

Map的遍历

Map<String, String> map = new HashMap<>();
map.put("dolphin", "海豚");
map.put("octopus", "章鱼");

Set<String> keys = map.keySet();

// 1. 增强for
for (String key : keys) {
    System.out.println(key + " : " + map.get(key));
}

System.out.println("================================================");

// 2. 迭代器
Iterator<String> iterator = keys.iterator();
while (iterator.hasNext()) {
    String key = iterator.next();
    System.out.println(key + " : " + map.get(key));
}

System.out.println("================================================");

// 3. EntrySet
for (Map.Entry<String, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " : " + entry.getValue());
}