我有一个简单的元组类。
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 权重等。过了一段时间,只看到 first
和 second
作为变量名称,就会变得困惑,当它们可能意味着诸如 name
和 id
之类的东西。有什么方法可以多次子类化该类,将 first
和 second
重命名为有意义的名称,而不需要重写 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/