14 Mayıs 2023 Pazar

JEP 359 record ve Comparable

Örnek
Şöyle yaparız
public record Point(int x, int y) implements Comparable<Point> {

  @Override
  public int compareTo(Point o) {
    if (o == null) {
      throw new NullPointerException();
    }

    return Comparator
      .comparingInt(Point::x)
      .thenComparingInt(Point::y)
      .compare(this, o);
  }
}

public record ExtendedPoint<T extends Comparable<T>>(T payload, int x, int y)
        implements Comparable<ExtendedPoint<T>> {
  @Override
  public int compareTo(ExtendedPoint<T> o) {
    if (o == null) {
      throw new NullPointerException();
    }

    return Comparator
      .comparingInt(ExtendedPoint<T>::x)
      .thenComparingInt(ExtendedPoint::y)
      .thenComparing(obj -> payload.compareTo(obj.payload))
      .compare(this, o);
  }
}

Hiç yorum yok:

Yorum Gönder