3

Is there something equivalent to C++ typedef/using in Java? In C++ I'd write

using LatLng = std::pair<double, double>;
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
marco
  • 243
  • 1
  • 9

2 Answers2

2

There are no type aliases in Java.

Nor is there anything like decltype.

eerorika
  • 232,697
  • 12
  • 197
  • 326
-4

The nearest thing to a decltype is probably dealt with using generics in java.

/**
 * @author OldCurmudgeon
 * @param <P> - The type of the first.
 * @param <Q> - The type of the second.
 */
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
  • I think the user wanted to know if there is something like type aliases in Java (such as 'using' used to allow the compiler to recognize a type by a different name). – Dave Doknjas Dec 22 '15 at 16:06