Java 优先级队列.pdfVIP

  • 6
  • 0
  • 约4.6千字
  • 约 7页
  • 2018-06-02 发布于河南
  • 举报
Java 优先级队列.pdf

Java 优先级队列 Java集合教程 - Java优先级队列 优先级队列是其中每个元素具有相关联的优先级的队列。具有最⾼优先级的元素将从 队列中删除。 PriorityQueue 是⼀个实现类对于Java Collection Framework 中的 界优先级队 列。 我们可以使⽤在每个元素中实现的 Comparable 接⼜作为其优先事项。 或者我们可以提供⼀个 Comparator 对象,这将确定元素的优先级顺序。 当向优先级队列添加新元素时,它将根据其优先级位于队列中。 PriorityQueue APIs 例⼦ import java.util.PriorityQueue; import java.util.Queue; class ComparablePerson implements ComparableComparablePerson { private int id; private String name; public ComparablePerson(int id, String name { this.id = id; = name; } public int getId( { return id; } public void setId(int id { this.id = id; } public String getName( { return name; } public void setName(String name { = name; } @Override public boolean equals(Object o { if (!(o instanceof ComparablePerson { return false; } ComparablePerson p = (ComparablePerson o; if (this.id == p.getId( { return true; } return false; } @Override public int hashCode( { return this.id; } @Override public String toString( { return ( + id + , + name + ; } @Override public int compareTo(ComparablePerson cp { int cpId = cp.getId( ; String cpName = cp.getName( ; if (this.getId( cpId { return -1; } if (this.getId( cpId { return 1; } if (this.getId( == cpId { return this.getName( .compareTo(cpName ; } // Should not reach here return 0; } } public class Main { public static void main(String[] args { QueueComparablePerson pq = new PriorityQueue( ; pq.add(new ComparablePerson(1, Oracle ; pq.add(new ComparablePerson(4, XML ; pq.add(new ComparablePerson(2, HTML ; pq.add(new ComparablePerson(3, CSS ; pq.add(new ComparablePerson(4, Java ; System.out.println(pq ; while (pq.peek(

文档评论(0)

1亿VIP精品文档

相关文档