有两种比较方法,一种是对象实现Comparable接口并覆写compareTo方法,另一种是定义实现Comparator接口的类。
如果只是判断是否相等,就覆写equals方法
1) Employee对象实现Comparable接口
public class Employee implements Comparable<Employee>{
/**员工姓名*/
private String name;
/**员工性别*/
private String sex;
/**员工年龄*/
private int age;
public Employee(String name,String sex,int age){//不再有默认空参构造啦
this.name = name;
this.sex = sex;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {//只比较员工姓名
Employee e = (Employee) obj;
return this.name.equals(e.name);//竟然可以在这直接调用私有属性
}
@Override
public String toString() {//打印,获取信息
return this.name+"-"+this.sex+"-"+this.age;
}
@Override
public int compareTo(Employee o) {//用年龄来比较
if(this.age == o.getAge())
return 0;
else if(this.age > o.getAge())
return 1;
else
return -1;
}
}
2) 或者使用Comparator方式
public class EmployeeComparator implements Comparator<Employee> {
@Override
public int compare(Employee o1, Employee o2) {
//充分利用三目运算符
int result = o1.getAge() == o2.getAge()?0:(o1.getAge()>o2.getAge()?1:-1);
return result;
}
}
3) 下面是使用到比较的例子
List<Employee> list = new ArrayList<Employee>();
list.add(new Employee("总监", "男", 30));
list.add(new Employee("项目经理", "男", 28));
list.add(new Employee("攻城狮", "男", 27));
list.add(new Employee("设计师", "女", 22));
list.add(new Employee("总经理", "男", 35));
list.add(new Employee("董事长", "男", 40));
// Collections.sort(list);//使用Comparable
Collections.sort(list, new EmployeeComparator());//使用Comparator
System.out.println(list);//调toString
Set<String> mSet = new TreeSet<String>();//排序,所插对象需实现Comparable接口
mSet.add("zhang");mSet.add("wang");mSet.add("li");
mSet.add("zhao");mSet.add("zhang");
System.out.println(mSet);
Map<Integer, String> map = new TreeMap<Integer, String>();//排序,所插对象需实现Comparable接口
map.put(4, "washing machine");
map.put(1, "television");
map.put(2, "watch");
map.put(3, "refrigerator");
map.put(5, "computer");
System.out.println(map);
4)Comparable和Comparator的差别
Comparable需要比较的类本身实现此接口,Comparator不需要。
String是final类,本身实现了Comparable接口,但不能被继承。即如果我们对其compareTo方法不满意,又不能覆写它。只能使用Comparator了。
5)一些实用的方法
Collections.addAll(Collection<String>, String[])。将数组转化为Collection,或理解为将数组中的数据全部添加到Collection
Arrays.asList(String[])。将数组转化为List,List.toString方便查看所有数据
Collection.toArray(). 将Collection转化为数组,数组遍历效率较高
Collections.sort(List)及Collections.sort(List,Comparator). 对List排序
Collections.shuffle(List)及Collections.shuffle(List,Random). 将List顺序打乱
6)使用Comparator对Map和Set排序,即使用new TreeMap(Comparator)和new TreeSet(Comparator)
public class StringComparator implements Comparator<String> {
@Override
public int compare(String lhs, String rhs) {
String[] str1 = lhs.split("\\.");
String[] str2 = rhs.split("\\.");
for(int i=0;i<str1.length-1;i++){
int int1 = Integer.parseInt(str1[i]);
int int2 = Integer.parseInt(str2[i]);
if(int1>int2){
return 1;
}else if(int1<int2){
return -1;
}
}
return 0;
}
}
Map<String, Set<String>> map = new TreeMap<String, Set<String>>(new StringComparator());
String[] data = {"1.1.html","4.77.html","10.55.html","2.33.html","1.html","4.html","1.5.html","10.html","2.html"};
for(int i=0;i<data.length;i++){
if(data[i].indexOf('.')!=data[i].lastIndexOf('.')){
String key = data[i].substring(0, data[i].indexOf('.'))+data[i].substring(data[i].lastIndexOf('.'));
if(map.get(key)==null){
map.put(key, new TreeSet<String>(new StringComparator()));
}
map.get(key).add(data[i]);
}
}
TreeMap实现Navigable接口,有几个实用的方法:lowerKey, higherKey, floorKey, ceilingKey.
TreeSet实现SortedSet接口,有几个实用方法:first(), last().