zoukankan      html  css  js  c++  java
  • Java集合类总结 (四)

    PriorityQueue类

    优先队列不管你按照什么顺序插入元素,出队列的时候元素都是按顺序输出的。也就是每次调用remove的时候,都返回当前队列中最小的元素。然后队列中的元素不是维持排序状态的,如果你迭代这个优先队列中的元素,会发现他们不是排好序的。

    优先队列使用堆数据结果,堆是一种自我调整的二叉树,对树的add与remove操作可以让最小的元素移动到树的根部。

    使用优先队列的典型示例是任务调度,每个任务都有一个优先级,任务以随机顺序添加到队列中。每当启动一个新的任务时,都将优先级最高的任务从队列中取出进行处理

    PriorityQueue<GregorianCalendar> pq = new PriorityQueue<>();
    pq.add(new GregorianCalendar(1906, Calendar.DECEMBER, 9)); 
    pq.add(new GregorianCalendar(1815, Calendar.DECEMBER, 10)); 
    pq.add(new GregorianCalendar(1903, Calendar.DECEMBER, 3)); 
    pq.add(new GregorianCalendar(1910, Calendar.JUNE, 22)); 
    System.out.println("Iterating over elements...");
    for (GregorianCalendar date : pq)
    {
         System.out.println(date.get(Calendar.YEAR));
    }
    System.out.println("Removing elements...");
    while (!pq.isEmpty())
    {
         System.out.println(pq.remove().get(Calendar.YEAR));
    }
    

    输出结果:

    Iterating over elements...
    1815
    1906
    1903
    1910
    Removing elements...
    1815
    1903
    1906
    1910
    

     

    Maps类

    Java类库提供两种maps实现:HashMap与TreeMap,他们都实现了Map接口。
    哈希(hash)函数与比较函数仅应用于map的key上, map的value只是key的一个关联, value不会进行哈希与比较。

    使用HashMap存储元素:

    Map<String, Employee> staff = new HashMap<>(); // HashMap implements Map
    Employee harry = new Employee("Harry Hacker");
    staff.put("987-98-9996", harry);
    . . .
    
    • Map有三种view:
      • the set of keys
      • the collection of values (which is not a set)
      • the set of key/value pairs.
        The keys and key/value pairs form a set because there can be only one copy of a key in a map
    Set<K> keySet()
    Collection<K> values()
    Set<Map.Entry<K, V>> entrySet()
    

    迭代所有map中的key:

    Set<String> keys = map.keySet();
    for (String key : keys)
    {
        do something with key
    }
    

    迭代map中的key和value:

    for (Map.Entry<String, Employee> entry : staff.entrySet())
    {
       String key = entry.getKey();
       Employee value = entry.getValue();
       do something with key, value
    }
  • 相关阅读:
    Python之 continue继续循环
    Python之 break退出循环
    Python之 while循环
    Python之 for循环
    java中collection、map、set、list简介 (转)
    CloudSim介绍和使用
    智能指针和动态内存
    boost signal2
    boost 信号 :
    boost库 线程使用
  • 原文地址:https://www.cnblogs.com/liupengblog/p/5182036.html
Copyright © 2011-2022 走看看