-4

I am new to Java. Can someone explain to me what is the difference between using lambda and method here?

Method equals()

  @Override
  public boolean equals(Object o) {

    if (this == o) {
      return true;
    }
    if (!(o instanceof Book)) {
      return false;
    }

    Book book = (Book) o;

    if (!author.equals(book.author)) {
      return false;
    }
    return title.equals(book.title);
  }

Lambda equals()

  public Function<Object, Boolean> equals = (Object o) -> {
    if (this == o) {
      return true;
    }
    if (!(o instanceof Book)) {
      return false;
    }

    Book book = (Book) o;

    if (!author.equals(book.author)) {
      return false;
    }
    return title.equals(book.title);
  };

Method hashCode()

  @Override
  public int hashCode() {
    return 31 * author.hashCode() + title.hashCode();
  }

Lamba hashCode()

  public Supplier<Integer> hashCode = () -> 31 * author.hashCode() + title.hashCode();

I wanted to use Lambda instead of method for equals and hashCode.

Is it OK?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
createdbyjurand
  • 1,177
  • 1
  • 6
  • 6
  • 2
    Method is method, lambda is *instance* representing some functional interface like in your case `Supplier`. Those are entirely different things. – Pshemo Sep 26 '21 at 10:43

1 Answers1

6

No, it is not OK. Java defines the methods boolean equals(Object) and int hashCode(). This is a specific signature and your suggested solution doesn't meet that signature and doesn't override the default implementation from Object (in fact, they are not even methods).

You could use a lambda in your equals and hashCode, but that would just add a needless level of indirection, and make your code harder to read.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197