Comparator 比較器接口

public class Student
java

{this

private String name;spa

private int age ;.net

public Student(String name, int age)接口

{get

super();it

this.name = name;class

this.age = age;import

}im

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;

}

}

public String toString()

{

return name + "\t\t"+age;

}

public String getName()

{

return name;

}

public void setName(String name)

{

this.name = name;

}

public int getAge()

{

return age;

}

public void setAge(int age)

{

this.age = age;

}

}

//定義一個學生類

//這是一個學生類接口

import java.util.Comparator;

public class StudentComparator implements Comparator<Student>

{

public int compare(Student s1,Student s2)

{

if (s1.equals(s2))

{

return 0;

} else if(s1.getAge()<s2.getAge())

{

return -1;

}else {

return 1;

}

}

}

//對學生進行年齡從大到小排列

import java.util.Arrays;


public class ComparatorDemo

{


/**

* @param args

*/

public static void main(String[] args)

{

Student [] str = {new Student("cao", 20),new Student("wang", 23),

new Student("yang", 34),new Student("liu", 21)};

Arrays.sort(str,new StudentComparator());

for (int i = 0; i < str.length; i++)

{

System.out.println(str[i]);

}

}


}

相關文章
相關標籤/搜索