码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA优先级队列测试

时间:2017-09-07 21:31:27      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:迭代   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优先级队列测试

标签:迭代   tostring   原来   main   asn   输出   new   add   priority   

原文地址:http://www.cnblogs.com/chenggang816/p/7491712.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!