What's the nearest substitute for a function pointer in Java?

前端 未结 22 1865
太阳男子
太阳男子 2020-11-22 15:32

I have a method that\'s about ten lines of code. I want to create more methods that do exactly the same thing, except for a small calculation that\'s going to change one li

22条回答
  •  盖世英雄少女心
    2020-11-22 16:28

    Prior to Java 8, nearest substitute for function-pointer-like functionality was an anonymous class. For example:

    Collections.sort(list, new Comparator(){
        public int compare(CustomClass a, CustomClass b)
        {
            // Logic to compare objects of class CustomClass which returns int as per contract.
        }
    });
    

    But now in Java 8 we have a very neat alternative known as lambda expression, which can be used as:

    list.sort((a, b) ->  { a.isBiggerThan(b) } );
    

    where isBiggerThan is a method in CustomClass. We can also use method references here:

    list.sort(MyClass::isBiggerThan);
    

提交回复
热议问题