概论
在平时编码时免不了要进行各种比较,java内置了Comparable接口,我们可以实现这个接口,然后进行比较,int,double等基础类型不能进行这样比较,必须使用其包装类Integer等。
Demo:
import java.awt.Shape;
class Student implements Comparable<Student>
{
private String name;
private int score;
public Student(String name, int score) {
super();
this.name = name;
this.score = score;
}
public int getScore() {
return score;
}
@Override
public int compareTo(Student o) {//o为所比较的对象
if(o.getScore()<score) //比较的条件
return 1; //符合返回1
else
return 0; //不符合返回0
}
@Override
public String toString() {
return "Student [name=" + name + ", score=" + score + "]";
}
}
public class CompareTo {
public static <T> Comparable<T> findMax(Comparable<T>[] arr)
{
int maxIndex = 0;
for (int i = 0; i < arr.length; i++) {
if(arr[i].compareTo((T) arr[maxIndex])>0)//如果返回值大于0,则maxindex = i;
maxIndex = i;
}
return arr[maxIndex];//最后返回最大的
}
public static void main(String[] args) {
Integer[] in = {1,2,3,4,5,7,6};
System.out.println(findMax(in));
String [] st = {"Joe","Bob","Bill","ZZZZZ"};
System.out.println(findMax(st));
// int [] s = {1,2,3,4,5,7,6};
//System.out.println(findMax(s));
//错误因为其只能用于实现了compare接口的类中
Student[] stu = {new Student("one", 90),
new Student("two", 100),
new Student("three", 95)};
System.out.println(findMax(stu));
}
}
Result
7
ZZZZZ
Student [name=two, score=100]