内容是讲TreeSet的自定义比较器,有个小小的疑问,希望大牛们帮我解决。
代码如下:package com.joe.list;
import java.util.Comparator; import java.util.Iterator; import java.util.TreeSet;
/** * 当元素自身不具备比较性,或者具备的比较性不是所需要的。这时需要让容器自身具备比较性。 定义了比较器,将比较器对象作为参数传递给TreeSet集合的构造函数 * * @author joe * */
public class TreeSetDemo2 { public static void main(String[] args) { TreeSet ts = new TreeSet(new MyCompare()); ts.add(new Student2("lisi",23)); ts.add(new Student2("lisi1",22)); ts.add(new Student2("lisi2",24)); ts.add(new Student2("lisi3",21)); Iterator it = ts.iterator(); while(it.hasNext()){ Student2 stu = (Student2)it.next(); System.out.println(stu.getName()+"..."+stu.getAge()); } }
}
//自定义比较器 class MyCompare implements Comparator{ public int compare(Object o1,Object o2){ Student2 s1 = (Student2)o1; Student2 s2 = (Student2)o2; int num = s1.getName().compareTo(s2.getName()); if(num==0) { //问题:这里他改为用new Integer对象封装,为啥要封装呢? return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge())); // if(s1.getAge()>s2.getAge()) // return 1; // if(s1.getAge()==s2.getAge()) // return 0; // return -1; } return num; } }
class Student2 implements Comparable { private String name; private int age;
public Student2(String name, int age) { super(); this.name = name; this.age = age; }
public Student2() { super(); }
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 String toString() { return "Student [name=" + name + ", age=" + age + "]"; }
@Override public int compareTo(Object obj) { if (!(obj instanceof Student2)) throw new RuntimeException("不是学生对象"); Student2 s = (Student2) obj;
if (this.age > s.age) { // 先比较年龄 return 1; } else if (this.age < s.age) { return this.name.compareTo(s.name); // 如果年龄相同,在比较名字 } return -1; } }
|