Superclass Object

  • Superclass of all Java classes.

  • Common methods to be redefined by derived classes.

String literals

layered SVG image

String literals

layered SVG image

String literals

layered SVG image

String literals

layered SVG image

OpenJDK String implementation

Implementation of java.lang.String:

public final class String ... {
  private final char value[];
  private int hash;
  private static final long serialVersionUID = -6849794470754667710L;
...
}

String copy constructor

String s = new String("Eve");

Uses constructor public String(String original).

Copy constructor and heap

layered SVG image

Copy constructor and heap

layered SVG image

Copy constructor and heap

layered SVG image

Copy constructor and heap

layered SVG image

Copy constructor and heap

layered SVG image

Copy constructor and heap

layered SVG image

Operator == and equals()

Primitive type Object
int a = 12, b = 12;  // equal values

System.out.println("==: " + (a == b));
// No equals(...) method equivalent 
// for primitive types
String s1 = new String("Kate"),
       s2 = new String("Kate");

System.out.println("    ==: " + (s1 == s2));
System.out.println("equals: " + s1.equals(s2));
==: true
    ==: false
equals: true

Remarks == vs. equals()

  • The == operator acting on primitive types compares expression values.

  • The == operator acting on objects compares for equality of reference values and thus for object identity.

  • The == operator acting on objects does not check whether two objects carry semantically equal values.

  • The equals() method compares two object's values.

Hashing principle

Hashing principle
I want the 12p one

Quickly identify by simple value

  • Where is the blond haired guy?

  • I take the pink flower.

  • The 334.50$ cellular phone.

Hashing in Java and equals()

Method hashCode(): Instance 0 ⇨ o.hashCode(), of type int.

  • Same value on repeated invocation

  • Objects with identical value with respect to equals() must have identical hash values:

    true == a.equals(b)a.hashCode() == b.hashCode().

  • Conversely: Two instances differing with respect to equals() may have identical hash values.

Consequence: equals() and hashCode() must be redefined simultaneously!

Rectangle equals(...) and hashCode()

public class Rectangle {
    int width, height;
    @Override public boolean equals(Object o) {
        if (o instanceof  Rectangle) {
            return width == ((Rectangle) o).width
                    && height == ((Rectangle) o).height;
        } else {
            return false;
        }
    }
    @Override public int hashCode() {
        return width + height;
    }
}

Rectangle hash values

width height hash value
1 3 4
2 2 4
5 5 10
2 7 9
4 9 13

Better hashCode() method

public class Rectangle {
    int width, height;
...
    @Override public int hashCode() {
        return width + 13 * height;
    }
}

Followup exercises