generic compareTo排序不同的对象类

时间:2014-09-29 19:15:48

标签: java generics

我正在尝试使用compareTo来返回各种类型对象的最大或最大值。这适用于整数,字符串,但是当我尝试包含圆圈时我正在...

如何获得一个通用方法来比较所有对象?在这种情况下,圆圈只有一个变量radius,以便比较......



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

2 个答案:

答案 0 :(得分:1)

&#34;如何获得一种比较所有对象的通用方法?&#34;

没有一种通用的比较对象的方法,这就是为什么compareTo和Comparable一开始就做出来的原因。考虑班上的学生,我可以根据身高,分数,年龄进行比较......

只需创建一个你想要的概念(比如说一个圆圈),实现Comparable并定义compareTo来定义你如何比较该Object的标准。例如:

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

答案 1 :(得分:0)

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