Skip to content
Advertisement

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

I have the following class:

JavaScript

My implementation currently work like this:

JavaScript

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

JavaScript

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:

JavaScript

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

Advertisement

Answer

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

JavaScript

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

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement