加载中...
第11章 集合
发表于:2021-06-15 | 分类: 《Java编程思想》读书笔记
字数统计: 562 | 阅读时长: 2分钟 | 阅读量:

11.2 基本概念

Collection接口:

  • List接口:
    • LinkedList:链表,没有同步,线程不安全
    • ArrayList:数组,没有同步,线程不安全
    • Vector:数组,同步,线程安全
      • Stack:继承Vector,线程安全
  • Set接口:不可重复,内部排序
    • HashSet:散列函数
      • LinkedHashSet:链表维护元素的插入次序
    • TreeSet:底层为红黑树,自动升序排序保存

Map接口:

  • HashMap:查找最快,无顺序 ,没有同步, 线程不安全
    • LinkedHashMap:保留HashMap的速度,按照插入顺序保存
  • TreeMap:红黑树,自动升序排序保存
  • Hashtable:接口实现类, 同步, 线程安全

11.3 Collection接口方法


11.5 List接口


11.6 迭代器Iterator

Iterator:

  • iterator() 返回一个iterator,将准备好返回序列第一个元素
  • next() 获得序列下一个元素
  • hasNext() 判断序列是否还有元素
  • remove()将迭代器返回的元素删除
1
2
3
4
5
Iterator<...> it = a.iterator();
while(it.hasNext()){
print(it.next());
it.remove();
}

如果只想遍历List,不想修改,应该用foreach

11.6.1 ListIterator


11.9 Set

Set和List的区别:

  • List元素可以重复,Set不能重复
  • List可以根据索引操作元素,Set不能
  • List按照插入顺序保存,Set不一定

11.10 Map


11.11 Queue

Collection-》Queue-》LinkedList
创建一个队列:Queue<...> queue = new LinkedList<...>()

Queue方法

  • 继承自Collection,特殊方法如下:
    • boolean offer() 将元素插入队尾,或返回false
    • E peek() 返回队头,若队列为空则返回null
    • E poll() 删除队头并返回,若队列为空返回null

11.11.1 PriorityQueue

  • 自定义优先级比较器,作为优先队列构造器的参数。
  • 优先队列继承自Queue,有同样的方法。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    //自定义比较器,降序排列
    static Comparator<Integer> cmp = new Comparator<Integer>() {
    public int compare(Integer e1, Integer e2) {
    return e2 - e1;
    }
    };
    public static void main(String[] args) {
    //不用比较器,默认升序排列
    Queue<Integer> q = new PriorityQueue<>();
    q.add(3);
    q.add(2);
    q.add(4);
    while(!q.isEmpty())
    {
    System.out.print(q.poll()+" ");
    }
    /**
    * 输出结果
    * 2 3 4
    */
    //使用自定义比较器,降序排列
    Queue<Integer> qq = new PriorityQueue<>(cmp);
    qq.add(3);
    qq.add(2);
    qq.add(4);
    while(!qq.isEmpty())
    {
    System.out.print(qq.poll()+" ");
    }

    }
上一篇:
第12章 异常
下一篇:
第10章 内部类
本文目录
本文目录