2014-09-29 48 views
0

我想用compareTo来返回各种类型的对象的最大或最大值。这适用于整数,字符串,但我有,当我尝试包括圆...generic compareTo排序不同的对象类

如何获得一个通用方法来比较所有对象?在这种情况下,界只有一个变量,半径,比较...

public class CompareToVariousObjects { 
 
\t public static void main(String[] args) { 
 
\t \t 
 
\t Integer[] numbers = {1, -2, 3, 0, -1, 2, -3}; 
 
\t String[] colors = {"blue", "green", "white", "red", "black"}; 
 
\t Circle[] circles = {new Circle(5.9), new Circle(.5), new Circle(1), 
 
\t \t \t new Circle(2.5), new Circle(.1)}; 
 
\t 
 
\t System.out.println("Numerically, the maximum number is: " + max(numbers)); 
 
\t System.out.println("Alphabetically, the maximum color is: " + max(colors)); 
 
\t System.out.println("The largest circle has a radius of: " + max(circles); 
 
\t } 
 
\t 
 
\t public static <T extends Comparable<T>> T max(T[] list) { 
 
\t \t T currentMax = null; 
 
\t \t int currentMaxIndex; 
 
\t \t \t \t 
 
\t \t for (int i = 0; i < list.length - 1; i++) { 
 
\t \t \t currentMax = list[i]; 
 
\t \t \t currentMaxIndex = i; 
 
\t \t \t 
 
\t \t \t for (int j = i + 1; j < list.length; j++) { 
 
\t \t \t \t if (currentMax.compareTo(list[j]) > 0) { 
 
\t \t \t \t \t currentMax = list[j]; 
 
\t \t \t \t \t currentMaxIndex = j; 
 
\t \t \t \t } 
 
\t \t \t } 
 
\t \t \t 
 
\t \t \t if (currentMaxIndex != i) { 
 
\t \t \t \t list[currentMaxIndex] = list[i]; 
 
\t \t \t \t list[i] = currentMax; 
 
\t \t \t } 
 
\t \t } 
 
\t \t return currentMax; 
 
\t } 
 
}

+1

您可以直接使用'Collections.max'。 – aioobe 2014-09-29 19:20:56

+0

哪个版本的Java? – aioobe 2014-09-29 19:21:23

+0

你的方法不关心对象是整数,字符串,圆,香蕉或鱼。唯一重要的是它们都是Comparable的实例,所以它们总是可以相互比较。顺便说一句,你为什么要重新实现'Collections.max()'(http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#max%28java.util.Collection %29)?为什么dos方法返回一个数组的最大元素修改这个数组? – 2014-09-29 19:21:42

回答

1

“我怎样才能得到一个通用的方法来比较的所有对象?”

没有一种通用的方法来比较对象,这就是为什么compareTo和Comparable是首先做出来的。考虑一个班级的学生,我可以根据身高,分数,年龄来比较他们...

只需制作一个我们想要的概念类(比如说一个圆圈),然后实现Comparable并定义compareTo来定义你比较那个对象。例如:

public class Circle implements Comparable<Circle> { 
int diameter; 
//constructor 
public int compareTo(Circle c) { 
    if(c.diameter> this.diameter){ 
    return 1; 
    }else if .... 
0

您必须在Circle中实现Comparable接口。