自定义对象中sort函数的使用——JAVA
日期: 2020-01-13 分类: 个人收藏 360次阅读
方法一:
在自定义对象中使用comparable接口,并且定义compareTo()方法。
返回1 <返回-1 =返回0(若需要反序则>返回-1 <返回1 =返回0)
方法二:
新建Comparator类,在该类中实现compare()方法
返回1 <返回-1 =返回0(若需要反序则>返回-1 <返回1 =返回0)
然后再sort函数中调用Comparator类
方法一样例
import java.util.Arrays;
public class Person implements Comparable<Person> {
String name;
int age;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public int compareTo(Person another) {
int i = 0;
i = name.compareTo(another.name); // 使用字符串的比较
if (i == 0) {
// 如果名字一样,比较年龄, 返回比较年龄结果
return age - another.age;
} else {
return i; // 名字不一样, 返回比较名字的结果.
}
}
public static void main(String... a) {
Person[] ps = new Person[3];
ps[0] = new Person("Tom", 20);
ps[1] = new Person("Mike", 18);
ps[2] = new Person("Mike", 20);
Arrays.sort(ps);
for (Person p : ps) {
System.out.println(p.getName() + "," + p.getAge());
}
}
}
方法二样例:
public class Person2 {
private String name;
private int age;
public String getName() {
return name;
}
public int getAge() {
return age;
}
public Person2(String name, int age)
{
this.name = name;
this.age = age;
}
}
import java.util.Arrays;
import java.util.Comparator;
public class Person2Comparator implements Comparator<Person2> {
public int compare(Person2 one, Person2 another) {
int i = 0;
i = one.getName().compareTo(another.getName());
if (i == 0) {
// 如果名字一样,比较年龄,返回比较年龄结果
return one.getAge() - another.getAge();
} else {
return i; // 名字不一样, 返回比较名字的结果.
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Person2[] ps = new Person2[3];
ps[0] = new Person2("Tom", 20);
ps[1] = new Person2("Mike", 18);
ps[2] = new Person2("Mike", 20);
Arrays.sort(ps, new Person2Comparator());
for (Person2 p : ps) {
System.out.println(p.getName() + "," + p.getAge());
}
}
}
参考中国大学mooc——《java核心技术》
除特别声明,本站所有文章均为原创,如需转载请以超级链接形式注明出处:SmartCat's Blog
精华推荐