SE450: Taxonomy: Immutable Data Classes [55/63] Previous pageContentsNext page

We already have seen a basic version: Person.

Here is a more robust example:

file:Main.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
package basics.immutabledata;
public class Main {
  private Main() {}
  static public void main (final String[] args) {
    //stdlib.Trace.graphvizShowSteps (true); stdlib.Trace.run ();
    System.out.println(new Pair<>(42, "dog"));
  }
}

file:Pair.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package basics.immutabledata;
final public class Pair<S extends Comparable<S>, T extends Comparable<T>>
implements Comparable<Pair<S,T>>
{
  final private S x;
  final private T y;
  public Pair(S x, T y) {
    if (x == null || y == null)
      throw new IllegalArgumentException();
    this.x = x;
    this.y = y;
  }
  public S first() { return x; }
  public T second() { return y; }
  public String toString() { return "Pair(" + x + "," + y + ")"; }
  public boolean equals(Object thatObject) {
    if (thatObject == null)
      return false;
    if (this == thatObject)
      return true;
    // equals should not throw ClassCastException
    if (!(this.getClass().equals(thatObject.getClass())))
      return false;
    @SuppressWarnings("unchecked")
    Pair<S,T> that = (Pair<S,T>) thatObject;
    return x.equals(that.x)
        && y.equals(that.y);
  }
  private int hcode;
  public int hashCode() {
    if (hcode == 0) {
      hcode = 17;
      hcode = 37*hcode + x.hashCode();
      hcode = 37*hcode + y.hashCode();
    }
    return hcode;
  }
  public int compareTo(Pair<S,T> that) {
    // compareTo may throw ClassCastException
    int ix = x.compareTo(that.x);
    if (ix != 0)
      return ix;
    return y.compareTo(that.y);
  }
}

Previous pageContentsNext page