TreeSet判断元素的惟一性的方法:compareTo方法的返回值,当返回值为0时,就是相同元素,不存。
//定义一个类,实现Comparable接口,重写接口的CompareTo方法。就可以让该类按照我们重写的方法进行判断元素相同与否。
- import java.util.*;
- class Person implements Comparable{
- private String name;
- private int age;
- public Person(){}
- public Person(String name,int age){
- this.name = name;
- this.age = age;
- }
- public void setName(String name){
- this.name = name;
- }
- public void setAge(int age){
- this.age = age;
- }
- public String getName(){
- return this.name;
- }
- public int getAge(){
- return this.age;
- }
- public int hashCode(){
- return name.hashCode()+age*23;
- }
- public boolean equals(Object obj)
- {
- //传人两个相同的对象
- if(this == obj)
- return true;
- if(!(obj instanceof Person))
- throw new ClassCastException("类型错误");
- Person p = (Person)obj;
- return this.name.equals(p.name)&&this.age == p.age;
-
- }
- public int compareTo(Object o){
- Person p = (Person)o;
- //先按照年龄排序,在按照姓名排序,以免年龄相同的人没有存进去
- int temp = this.age-p.age;
- return temp == 0?this.name.compareTo(p.name):temp;//这里的this.name是字符串,String类也实现了Comparable方法
- }
- }
- public class TreeSetDemo{
- public static void main(String[] args){
- TreeSet ts = new TreeSet();
- //Person对象年龄从小到大进行排序
- ts.add(new Person("zs",23));
- ts.add(new Person("ls",32));
- ts.add(new Person("ww",43));
- ts.add(new Person("zl",4));
- ts.add(new Person("tq",43));
- Iterator it = ts.iterator();
- while(it.hasNext()){
- Person p = (Person)it.next();
- System.out.println(p.getName()+"…"+p.getAge());
- }
- }
- }
复制代码 |
|