equals(...) und hashCode()

exercise No. 257

F:

Wir betrachten folgende Rectangle Klasse:

public class Rectangle {
    private final int width, height;
    private final boolean hasSolidBorder;

    public Rectangle(final int width, final int height,
                     final boolean hasSolidBorder) {
        this.width = width;
        this.height = height;
        this.hasSolidBorder = hasSolidBorder;
    }
    @Override
    public boolean equals(final Object obj) {
        if (obj instanceof final Rectangle other) {
            return width == other.width
               &&  height == other.height;
        } else {
            return false;
        }
    }
}

Welche der nachfolgenden hashCode() Methodenvorschläge sind mit der Implementierung obiger equals(...) Methode kompatibel?

  1. @Override public int hashCode() {
    	      return height + (int)
    	      Math.round(Math.sqrt(width * width));}
  2. @Override public int hashCode() {
    	      return 0;}
  3. @Override public int hashCode() {
    	      return -1;}
  4. @Override public int hashCode() {
    	      return new String(
    	      "" + width + hasSolidBorder).hashCode();}
  5. @Override public int hashCode() {
    	      return new String().hashCode();}
  6. @Override public int hashCode() {
    	      return new String("" +
    	      height).hashCode();}
  7. @Override public int hashCode() {
    	      return height;}
  8. @Override public int hashCode() {
    	      return new Random().nextInt();}

Achtung

  • Jede angekreuzte richtige Antwort ergibt einen Punkt.

  • Jede angekreuzte Falschantwort ergibt drei Punkte Abzug.