JAVA優先順序隊列測試

來源:互聯網
上載者:User

標籤:迭代   tostring   原來   main   asn   輸出   new   add   priority   

package code.test;import java.util.Comparator;import java.util.Iterator;import java.util.PriorityQueue;import java.util.Queue;/** * 實驗表明,在java中: * 1.優先順序隊列列印或者迭代,得到的輸出順序為堆結構數組的順序,大致有序但不完全保證順序 * 2.由於堆排序是不穩定排序,在優先順序相同的情況下,元素不會保持原來的順序輸出 * Created by cg on 2017/9/7. */public class PriorityQueueTest {    public static void main(String[] args) {        Queue<Integer> queue = new PriorityQueue<Integer>();        queue.add(1);        queue.add(5);        queue.add(3);        queue.add(2);        queue.add(8);        queue.add(10);        queue.add(23);        queue.add(14);        System.out.println(queue); //輸出:[1, 2, 3, 5, 8, 10, 23, 14]        Iterator<Integer> iterator = queue.iterator();        while (iterator.hasNext()){            System.out.print(iterator.next() + " ");        }//輸出:1 2 3 5 8 10 23 14        System.out.println();        Queue<Student> queue1 = new PriorityQueue<Student>(new Comparator<Student>() {            @Override            public int compare(Student s1, Student s2) {                return s1.age - s2.age;            }        });        queue1.add(new Student("a", 14));        queue1.add(new Student("b", 12));        queue1.add(new Student("c", 12));        queue1.add(new Student("d", 12));        queue1.add(new Student("e", 12));        queue1.add(new Student("f", 13));        queue1.add(new Student("g", 11));        while (!queue1.isEmpty()){            System.out.println(queue1.poll());        }        /*輸出        g:11        c:12        d:12        e:12        b:12        f:13        a:14         */    }}class Student{    String name;    int age;    public Student(String name, int age) {        this.name = name;        this.age = age;    }    @Override    public String toString() {        return name + ":" + age;    }}

 

JAVA優先順序隊列測試

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.