如何实现Comparable接口来比较2个对象?

时间:2016-11-13 15:27:11

标签: java interface comparable

我正在尝试添加到这个程序,所以我可以使用Comparable接口比较两个有理数(稍后将在驱动程序类中定义)。但是当我使用public int compareTo时,它不允许我声明多于1个理性obbject。我怎么能这样做?

public class Rational implements Comparable <Rational, Rational>
{ 
     private int numerator; 
     private int denominator; 

public Rational (int numer, int denom) 
{ // begins block
  if (denom == 0) 
  denom = 1; 

if (denom < 0)
{ 
  numer = numer * -1; 
  denom = denom * -1; 
} 
numerator = numer; 
denominator = denom; 
reduce();
}

public int getNumerator ()
{ 
  return numerator; 
} 
public int getDenominator ()
{ // begins block
return denominator;  
} 
public Rational reciprocal ()  
{ // begins block
return new Rational (denominator, numerator); 
} 
public Rational add (Rational op2) 
{ // begins block
int commonDenominator = denominator * op2.getDenominator();
int numerator1 = numerator * op2.getDenominator();
int numerator2 = op2.getNumerator() * denominator; 
int sum = numerator1 + numerator2; 
return new Rational (sum, commonDenominator); 
} 
public Rational subtract (Rational op2)
{ // begins block
int commonDenominator = denominator * op2.getDenominator(); 
int numerator1 = numerator * op2.getDenominator(); 
int numerator2 = op2.getNumerator() * denominator; 
int difference = numerator1 - numerator2;
return new Rational (difference, commonDenominator); 
} 
public Rational multiply (Rational op2) 
{ // begins block
int numer = numerator * op2.getNumerator(); 
int denom = denominator * op2.getDenominator(); 
return new Rational (numer, denom); 
} 

public Rational divide (Rational op2)
{ // begins block
return multiply (op2.reciprocal()); 
}
public boolean equals (Rational op2) 
{ // begins block
return ( numerator == op2.getNumerator() && denominator ==      op2.getDenominator() ); 
}
public String toString () 
{ // begins block
String result; 
if (numerator == 0) 
  result = "0"; 
else 
  if (denominator == 1) 
  result = numerator + ""; 
else 
  result = numerator + "/" + denominator; 
return result; 
}
private void reduce () 
{ // begins block
if (numerator != 0) 
{ // begins block
  int common = gcd  
    (Math.abs(numerator), denominator);
     numerator = numerator / common; 
     denominator = denominator / common; 
} // ends block
} 
private int gcd (int num1, int num2) 
{
while (num1 != num2) 
  if (num1 > num2) 
  num1 = num1 - num2; 
else 
  num2 = num2 - num1; 
return num1; 
} 

public int compareTo (Rational r1, Rational r2)
{ 

Float value1 = new Float ((float)r1.getNumerator() / r1.getDenominator()); 
Float value2 = new Float ((float)r2.getNumerator() / r2.getDenominator());  

int answer = value1.compareTo(value2);
return answer;

}
} 

1 个答案:

答案 0 :(得分:4)

compareTo接口的Comparable方法只需要一个参数:要与之比较的其他实例。 因此它只需要一个类型参数。 修复你的类声明:

public class Rational implements Comparable<Rational>

遵循当前compareTo实施中的模式, 有一些小的改正和改进, 这是实现compareTo的{​​{1}}的一种方法:

Comparable