【问题标题】:C++ typedef in Java? [duplicate]Java中的C++ typedef? [复制]
【发布时间】:2016-03-28 22:24:59
【问题描述】:

在 Java 中是否有与 C++ typedef/using 等价的东西?在 C++ 中我会写

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

【问题讨论】:

  • 我有点好奇。它是做什么的?
  • Java 是一种简单、系统、一致、可学习的语言。它没有那个死去的古老遗物 C++ 所拥有的所有神秘的废话。
  • decltype,还是using?
  • using(或typedef)为一个类型创建一个别名。
  • Java 中没有类型别名——也就是说,Java 中无法通过不同的名称来引用类型(通用或非通用)。另外,不能说一个对象的类型与其他对象的类型相同(C++11 'decltype')。

标签: java c++


【解决方案1】:

Java 中没有类型别名。

也没有像decltype这样的东西。

【讨论】:

    【解决方案2】:

    最接近 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;
      }
    
    }
    

    【讨论】:

    • 我认为用户想知道 Java 中是否存在类似类型别名的东西(例如 'using' 用于允许编译器识别不同名称的类型)。
    猜你喜欢
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 2011-05-09
    相关资源
    最近更新 更多