java - 重命名子类中的变量

标签 java

我有一个简单的元组类。

public class Tuple<X, Y> { 
    public X first; 
    public Y second; 
    public Tuple(X x, Y y) { 
        this.first = x; 
        this.second = y; 
    }

    @Override
    public String toString() {
        return "(" + first + "," + second + ")";
    }

    @Override
    public boolean equals(Object other) {
        if (other == null) {
            return false;
        }
        if (other == this) {
            return true;
        }
        if (!(other instanceof Tuple)){
            return false;
        }
        Tuple<X,Y> other_ = (Tuple<X,Y>) other;
        return other_.first == this.first && other_.second == this.second;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((first == null) ? 0 : first.hashCode());
        result = prime * result + ((second == null) ? 0 : second.hashCode());
        return result;
    }
}

我在几个不同的环境中使用它。我有文章的元组及其 ID、ID 和 vector 权重等。过了一段时间,只看到 firstsecond 作为变量名称,就会变得困惑,当它们可能意味着诸如 nameid 之类的东西。有什么方法可以多次子类化该类,将 firstsecond 重命名为有意义的名称,而不需要重写 toString(), equals()hashCode()

最佳答案

您可以子类化Tuple并添加具有有意义名称的额外getter。构造函数参数也被命名。您还可以通过在构造函数中将其声明为 int 来强制 id 不可为 null。

public class NameIdTuple extends Tuple<String, Integer> {

    public NameIdTuple(String name, int id) {
        super(name, id);
    }

    public String name() {
        return first;
    }

    public int id() {
        return second;
    }

}

仍然可以调用方法 getFirst()getSecond()(因此您具有完全的向后兼容性)。

我不知道您使用的是哪个 IDE,但 IntelliJ 的自动补全功能会以粗体显示类中声明的方法,其他例如 getClass()equals()getFirst() 不会以粗体显示,因此它们不太可能在新代码中使用。

关于java - 重命名子类中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33569756/

相关文章:

java - 错误 : Could not find or load main class application. 主要

java - 连接网络中的两个客户端

java - 通过java插件访问麦克风进行语音聊天

java - 如果我们通过一个线程添加并通过另一个线程删除,我们是否需要同步?

java - 将后台线程的结果传达给 Android 中的 Ui 线程的正确方法

java - 安装 java get_asdf_config_value : command not found 时出现 ASDF 错误

java - 不使用maven或gradle安装框架

java - Elasticsearch 6.4 : Mapping with RestHighLevelClient

java - 从java中的gradle.properties访问属性?

java - 如何创建一个使用 Java 中的二叉搜索树获取前一个节点的方法?