注:当Comparable与Comparator都存在时,以后者为参考来进行比较
Comparable
可比较接口,让某种数据类实现这个接口,就可以自定义比较方法
package test;
import java.util.*;
class Student implements Comparable<Student>{
private String name;
private int 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;
}
@Override
public int compareTo(Student o) {
int ret = name.compareTo(o.name);
if(ret == 0)
return new Integer(age).compareTo(new Integer(o.age));
return ret;
}
/**
* @param name
* @param age
*/
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
public class Test {
public static void main(String[] args) {
TreeSet<Student> ts = new TreeSet<Student>();
ts.add(new Student("Jack", 12));
ts.add(new Student("Jack", 13));
ts.add(new Student("Mike", 15));
ts.add(new Student("Amy", 25));
ts.add(new Student("Dog", 11));
for(Student tmp : ts) {
System.out.println(tmp);
}
}
}
Comparator
比较方法类,集合实例化的时候当做参数传入
例子:字符串按长度从小到大排序放入TreeSet,长度相等的话字典序小的排在前面
package test;
import java.util.*;
class LenComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
if(o1.length() > o2.length()) return 1;
if(o1.length() == o2.length())
return o1.compareTo(o2);
return -1;
}
}
public class Test {
public static void main(String[] args) {
TreeSet<String> ts = new TreeSet<String>(new LenComparator());
ts.add("abc");
ts.add("1233333");
ts.add("b");
ts.add("a");
ts.add("11");
for(String tmp : ts) {
System.out.println(tmp);
}
}
}
化简写法,有点乱,代码减少
package test;
import java.util.*;
public class Test {
public static void main(String[] args) {
TreeSet<String> ts = new TreeSet<String>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if(o1.length() > o2.length()) return 1;
if(o1.length() == o2.length())
return o1.compareTo(o2);
return -1;
}
});
ts.add("abc");
ts.add("1233333");
ts.add("b");
ts.add("a");
ts.add("11");
for(String tmp : ts) {
System.out.println(tmp);
}
}
}