work215.java
package test11;
import java.util.Arrays;
import java.util.Comparator;
public class work215
{
public static void main(String[] args)
{
Student stu[] = new Student[3];
stu[0] = new Student("果果", 14);
stu[1] = new Student("飞飞", 15);
stu[2] = new Student("糖糖", 13);
Arrays.sort(stu,new StudentComparator());
for (int i = 0; i < stu.length; i++)
{
System.out.println(stu[i]);
}
}
}
//类的内部没有实现Comparable接口,可以使用一下方式实现比较
class Student
{
private String name;
private int age;
public Student(String name,int age)
{
this.name = name;
this.age = age;
}
public void setName(String name)
{
this.name = name;
}
public void setAge(int age)
{
this.age = age;
}
public String getName()
{
return this.name;
}
public int getAge()
{
return this.age;
}
@Override
public String toString()
{
return this.name + "\t" + this.age;
}
public boolean equals(Object obj)
{
if(this == obj)
{
return true;
}
if (!(obj instanceof Student))
{
return false;
}
Student stu = (Student)obj;
if (stu.name.equals(this.name) && stu.age == this.age)
{
return true;
}
else
{
return false;
}
}
}
class StudentComparator implements Comparator<Student>
{
@Override
public int compare(Student o1, Student o2)
{
if (o1.equals(o2))
{
return 0; //相等
}
else if (o1.getAge() < o2.getAge())
{
return -1; //小于
}
else
{
return 1; //大于
}
}
}