0

Assuming the following class structure:

abstract class Animal<A extends Animal<A>> 
{
    ... someAbstractMethodDefinitions
}

class Duck<D extends Duck<D>> extends Animal<D> 
{
    public int getBeekSize()
    {
         return beekSize;
    }

    public int getHeadSize()
    {
         return headSize;
    }
}

class Mallard extends Duck<Mallard> 
{
    .. someCode
}

I then want to compare the ducks by beek size assuming I have a list of Ducks (not necessarily Mallards). In other words I want to do:

List<Duck> ducks = Arrays.asList(new Duck(), new Duck(), ...);
Collections.sort(
        ducks,
        Comparator.comparing(Duck::getBeekSize).reversed());

When I try to do this I get the compiler error: "Non-static method cannot be referenced in a static context". If I remove the .reversed() it works great and everything compiles and runs correctly. The following code works:

List<Duck> ducks = Arrays.asList(new Duck(), new Duck(), ...);
Collections.sort(
        ducks,
        Comparator.comparing(Duck::getBeekSize));

In other words why can I add a reversed() to my Comparator? The only difference between the two blocks of code is the .reversed() is removed.

Stephane Grenier
  • 15,006
  • 37
  • 109
  • 185
  • [I couldn't reproduce your problem](https://ideone.com/4sWfqO) with a [mcve] (MCVE). Can you post an MCVE? Or, if my example doesn't work for you, post which version of Java you're using. – Bernhard Barker Mar 24 '18 at 07:04

1 Answers1

1

you can find similar issue here: Comparator.reversed() does not compile using lambda

solution was to do something like this:

Collections.sort(ducks, Comparator.comparing((Duck d) -> d.getHeadSize()).reversed());

Edit:

adding related bugs with this issue:

https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8025138

https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8025290

LenosV
  • 197
  • 1
  • 6