0

I am making a simple unit tester, where i iterate on pairs of (input, expected) values, and check if a calculated actual value equals the expected.

This is perfectly doable in a simple HashMap<INPUTTYPE, OUTPUTTYPE>, but hash logic is pointless, since i'm going to iterate on all values, and never search in the map, while it would be nice to keep the order of the test cases (pairs of (input, expected)).

A List<Entry<K,V>> seems to work well, but it seems not nice to use an inner component of a Map in a List. It also seems unnatural to create the Pair class to connect input and expected, since Entry is the same thing.

Is there a way using existing java classes in the base libs that support this kind of data very well?

Attila Neparáczki
  • 466
  • 1
  • 6
  • 14

2 Answers2

1

A simple Pair would probably be your best choice:

/**
 * @author OldCurmudgeon
 * @param <P>
 * @param <Q>
 */
public class Pair<P extends Comparable<P>, Q extends Comparable<Q>> implements Comparable<Pair<P, Q>> {
  // Exposing p & q directly for simplicity. They are final so this is safe.
  public final P p;
  public final Q q;

  public Pair(P p, Q q) {
    this.p = p;
    this.q = q;
  }

  public P getP() {
    return p;
  }

  public Q getQ() {
    return q;
  }

  @Override
  public String toString() {
    return "<" + (p == null ? "" : p.toString()) + "," + (q == null ? "" : q.toString()) + ">";
  }

  @Override
  public boolean equals(Object o) {
    if (!(o instanceof Pair)) {
      return false;
    }
    Pair it = (Pair) o;
    return p == null ? it.p == null : p.equals(it.p) && q == null ? it.q == null : q.equals(it.q);
  }

  @Override
  public int hashCode() {
    int hash = 7;
    hash = 97 * hash + (this.p != null ? this.p.hashCode() : 0);
    hash = 97 * hash + (this.q != null ? this.q.hashCode() : 0);
    return hash;
  }

  @Override
  public int compareTo(Pair<P, Q> o) {
    int diff = p == null ? (o.p == null ? 0 : -1) : p.compareTo(o.p);
    if (diff == 0) {
      diff = q == null ? (o.q == null ? 0 : -1) : q.compareTo(o.q);
    }
    return diff;
  }

}
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
0

You could use 2 arrays and compare expected[i] with actual[i] if you don't want to create any new class as there isn't a standard Tuple/Pair in core java.

AdrianS
  • 1,980
  • 7
  • 33
  • 51