【发布时间】:2014-11-04 08:10:44
【问题描述】:
我正在研究一种在 Java 中称为 Pair 的抽象数据类型。它应该采用两个对象并将它们组合在此数据类型中。这应该需要不到 30 分钟,但我已经工作了 3 个半小时。我相信我的前两种方法是正确的,但我无法弄清楚反向或等于。您可以在代码中看到我尝试的内容:
public class Pair<T1,T2> implements PairInterface<T1,T2>
{
// TO DO: Your instance variables here.
public T1 first;
public T2 second;
public Pair(T1 aFirst, T2 aSecond)
{
first = aFirst;
second = aSecond;
}
/* Gets the first element of this pair.
* @return the first element of this pair.
*/
public T1 fst()
{
return this.first;
}
/* Gets the second element of this pair.
* @return the second element of this pair.
*/
public T2 snd()
{
return this.second;
}
/* Gets a NEW pair the represents the reversed order
* of this pair. For example, the reverse order of the
* pair (x,y) is (y,x).
* @return a NEW pair in reverse order
*/
public PairInterface<T2,T1> reverse()
{
return PairInterface<this.snd(),this.fst()>;//Pair<second;first>
}
/* Checks whether two pairs are equal. Note that the pair
* (a,b) is equal to the pair (x,y) if and only if a is
* equal to x and b is equal to y.
*
* Note that if you forget to implement this method, your
* compiler will not complain since your class inherits this
* method from the class Object.
*
* @param otherObject the object to be compared to this object.
* @return true if this pair is equal to aPair. Otherwise
* return false.
*/
public boolean equals(Object otherObject)
{
if(otherObject == null)
{
return false;
}
if(getClass() != otherObject.getClass())
{
return false;
}
if (otherObject.fst.equals(this.fst) &&
otherObject.snd.equals(this.snd))
{
return true;
} else {
return false;
}
}
/* Generates a string representing this pair. Note that
* the String representing the pair (x,y) is "(x,y)". There
* is no whitespace unless x or y or both contain whitespace
* themselves.
*
* Note that if you forget to implement this method, your
* compiler will not complain since your class inherits this
* method from the class Object.
*
* @return a string representing this pair.
*/
public String toString()
{
return "("+first.toString()+","+second.toString()+")";
}
}
【问题讨论】:
-
你说的“无法计算反向或等于”是什么意思?请更详细地解释。另外,请阅读FAQ 和How to Ask。您的书面问题听起来太像“请为我做这项工作”。
-
好吧,我先从equals开始。我假设它用于确定另一对是否等于这对,那么为什么它需要一个对象而不是一对?如何将随机对象与一对对象进行比较?
-
至于反向,它应该返回一个pairInterface,所以我认为我应该工作但编译器要求在this.snd()和this.fst()之间使用分号。这是为什么呢?
-
对于反向,看起来你的导师正试图在 javadoc 中给你一个重要的线索。
-
@GenericJon 谢谢线索是新的对吗?甚至没有意识到他在谈论新的关键字,这让我一头雾水。