C++ typedef in Java?

C++ typedef in Java?

本文关键字:Java in typedef C++      更新时间:2023-10-16

在Java中有类似于C++typedef/using的东西吗?用C++我会写

using LatLng = std::pair<double, double>;

Java中没有类型别名。

也没有类似decltype的东西。

最接近decltype的事情可能是使用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;
  }
}