简体   繁体   中英

Can I pass a field of a class to a constructor or a method?

I have the following class:

public abstract class Map {
    protected PriorityQueue<Node> openNodes;
}

My implementation currently work like this:

public Map() {
        PriorityQueue<Node> openNodes = new PriorityQueue<Node>((Node node1, Node node2) -> Integer.compare(node1.getFinalCost(), node2.getFinalCost()));
    }

However, I would like to use an implementation like this aswell:

public Map() {
        PriorityQueue<Node> openNodes = new PriorityQueue<Node>((Node node1, Node node2) -> Integer.compare(node1.getHeuristicCost(), node2.getHeuristicCost()));
    }

Is there any way to pass the heuristicCost or the finalCost fields of my Node class to the constructor to achieve these different behaviours? Something like this:

public Map(*fieldName*) {
        PriorityQueue<Node> openNodes = new PriorityQueue<Node>((Node node1, Node node2) -> Integer.compare(node1.get*fieldName*(), node2.get*fieldName*()));
    }

If not, could you suggest a solution to achieve this?

You can create a comparator from a method reference, using Comparator.comparingInt :

public Map(ToIntFunction<Node> compareBy) {
    this.openNodes = new PriorityQueue<>(Comparator.comparingInt(compareBy));
}

Then you can write new Map(Node::getFinalCost) or new Map(Node::getHeuristicCost) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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