2015-11-06 39 views
1

我有一个简单的元组类。重命名子类中的变量

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和他们的矢量重量等。一段时间后,它变得杂乱,只看到firstsecond作为变量名称,当他们可能意味着像nameid的东西。有没有什么办法可以多次继承这个类,以将firstsecond重命名为有意义的名称,而无需覆盖toString()equals()hashCode()

+0

你想创建一个使用变量名不在超类,但你仍然婉TOT使用''等于()''和''的hashCode()''从超类的子类? – Thevenin

+0

非常多,我只想看到有意义的名字,而不是第一和第二。 –

回答

1

您可以继承Tuple并添加额外的获得有意义的名称。另外构造函数参数被命名。你也可以强制id不能为空,在构造函数中声明它为int

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()不会为粗体,它是不可能的,他们将是用于新代码中。

+0

不错,这是我想要的。谢谢。 –

+0

很高兴我能帮忙:) –