我想用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 }
}
您可以直接使用'Collections.max'。 – aioobe 2014-09-29 19:20:56
哪个版本的Java? – aioobe 2014-09-29 19:21:23
你的方法不关心对象是整数,字符串,圆,香蕉或鱼。唯一重要的是它们都是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