Java 8 - Default Method for Colon Dual Syntax Call Interface

I delve into the innovations of Java 8, and I try to call the default method, which I implement in a higher-level interface, even if a subclass overrides it. I would not have a problem returning to implementation Comparatorin my class BusinessLogic, but I was wondering if there was any magic that allowed me to use the excellent one ::.

the code:

public interface IdEntity extends Comparable<IdEntity> {

    int getId();

    @Override
    default int compareTo(IdEntity other) {
        return getId() - other.getId();
    }
}

public class Game implements IdEntity {
    @Override
    public int compareTo(IdEntity o) {
        if (o instanceof Game) {
            Game other = (Game) o;
            int something;
            // logic
            return something;
        }
        return super.compareTo(o);
    }
}

public class BusinessLogic {
    private void sortList(List<? extends IdEntity> list) {
        // for Game, Game::compareTo gets called but I want, in this call only, the default method
        Collections.sort(list, IdEntity::compareTo);
    }
}
+4
source share
3 answers

One way is to put the comparison method in a static method:

public static interface IdEntity extends Comparable<IdEntity> {
  int getId();
  @Override default int compareTo(IdEntity other) {
    return defaultCompare(this, other);
  }
  static int defaultCompare(IdEntity first, IdEntity second) {
    return first.getId() - second.getId();
  }
}

Then your method will look like this:

Collections.sort(list, IdEntity::defaultCompare);
+6
source

Simplified Approach: Static Import Comparator.comparingIntand Use

Collections.sort(list, comparingInt(IdEntity::getId));

, compareTo: ; . .

+5

:

, , .. , . Java.

, , - , , , . , Game.compareTo IdEntity.compareTo IdEntity.super.compareTo, this.

super, this, this . . Game :

ToIntFunction<IdEntity> f=IdEntity.super::compareTo;

default IdEntity.compareTo Game, IdEntity.


. , abstract compareTo, Comparable, . -, . , Comparator . Game IdEntity, " " Comparator, , .

import java.util.Comparator;

public interface IdEntity /* not Comparable<IdEntity> */ {
    int getId();
    static Comparator<IdEntity> defaultOrder() {
        return Comparator.comparingInt(IdEntity::getId);
    }
}

Game :

public class Game implements IdEntity,Comparable<Game> {

    public int compareTo(Game o) {
        int something;
        // logic
        return something;
    }
    // …
}

Game IdEntity.defaultOrder():

import java.util.Comparator;

public class Game implements IdEntity {

    public static Comparator<Game> defaultGameOrder() {
        return (a,b) -> {
            int something;
            // logic
            return something;
        };
    }
    // …
}
+2

All Articles