Search code examples
javaoopstructure

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?


Solution

  • 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).