简体   繁体   English

我可以在 Java 中使用优先队列而不实现比较器吗?

[英]Can I use Priority Queue in Java without implementing a comparator?

如果我想创建节点的优先级队列,并且每个节点只有一个字段(即int val ),我是否必须为优先级队列编写一个比较器?

Yes.是的。 Assuming your Node class is your custom class, Java does not know how to compare two Nodes even if there's but one field in it.假设您的 Node 类是您的自定义类,即使其中只有一个字段,Java 也不知道如何比较两个 Node。 Therefore, you will need to do因此,你需要做

class Node implements Comparable<Node> {
    @Override
    public compareTo(Node other) {
        ...
    }
}

The elements of the priority queue are ordered according to their natural ordering, or by a Comparator .优先级队列的元素根据它们的自然顺序或 Comparator 进行排序。 If you don't want to use Comparator then implement Comparable in your Node class.如果您不想使用 Comparator,则在您的 Node 类中实现 Comparable。

No Comparator necessary.不需要Comparator You can create a PriorityQueue that relies on a class's "natural ordering".您可以创建一个依赖于类的“自然排序” PriorityQueue

Creates a PriorityQueue with the default initial capacity (11) that orders its elements according to their natural ordering .创建一个具有默认初始容量 (11) 的 PriorityQueue,它根据元素的自然顺序对其进行排序

That links to Comparable .链接到Comparable Make your Node class implement Comparable<Node> .使您的Node类实现Comparable<Node> Then you can use a PriorityQueue without a Comparator .然后您可以使用PriorityQueue而不使用Comparator

You don't necessarily need to implement Comparator in the Node class.您不一定需要在 Node 类中实现 Comparator。 You can use lambda expressions as detailed in the first part of this answer .您可以使用本答案第一部分中详述的 lambda 表达式。 I will modify that answer to fit into your question.我将修改该答案以适合您的问题。 For this to work you will have to create a getter method for the field that you have.为此,您必须为您拥有的字段创建一个 getter 方法。 Assuming that method is called "getVal()" This should work without needing to implement Comparator.假设该方法称为“getVal()”,这应该无需实现 Comparator 即可工作。

PriorityQueue<Node> pq=
            new PriorityQueue<Node>(Comparator.comparing(Node::getVal));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM