A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© 叶子和大人 中级黑马   /  2015-10-29 23:45  /  285 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

TreeSet判断元素的惟一性的方法:compareTo方法的返回值,当返回值为0时,就是相同元素,不存。
//定义一个类,实现Comparable接口,重写接口的CompareTo方法。就可以让该类按照我们重写的方法进行判断元素相同与否。

  1. import java.util.*;
  2. class Person implements Comparable{
  3.         private String name;
  4.         private int age;
  5.         public Person(){}
  6.         public Person(String name,int age){
  7.                 this.name = name;
  8.                 this.age = age;
  9.         }
  10.         public void setName(String name){
  11.                 this.name = name;
  12.         }
  13.         public void setAge(int age){
  14.                 this.age = age;
  15.         }
  16.         public String getName(){
  17.                 return this.name;
  18.         }
  19.         public int getAge(){
  20.                 return this.age;
  21.         }
  22.         public int hashCode(){
  23.                 return name.hashCode()+age*23;
  24.         }
  25.         public boolean equals(Object obj)
  26.         {
  27.                 //传人两个相同的对象
  28.                 if(this == obj)
  29.                         return true;
  30.                 if(!(obj instanceof Person))
  31.                         throw new ClassCastException("类型错误");

  32.                 Person p = (Person)obj;
  33.                         return this.name.equals(p.name)&&this.age == p.age;
  34.        
  35.         }
  36.         public int compareTo(Object o){
  37.                 Person p = (Person)o;
  38.                 //先按照年龄排序,在按照姓名排序,以免年龄相同的人没有存进去
  39.                 int temp = this.age-p.age;
  40.                 return temp == 0?this.name.compareTo(p.name):temp;//这里的this.name是字符串,String类也实现了Comparable方法
  41.         }
  42. }

  43. public class TreeSetDemo{
  44.         public static void main(String[] args){
  45.                 TreeSet ts = new TreeSet();
  46.                 //Person对象年龄从小到大进行排序
  47.                 ts.add(new Person("zs",23));
  48.                 ts.add(new Person("ls",32));
  49.                 ts.add(new Person("ww",43));
  50.                 ts.add(new Person("zl",4));
  51.                 ts.add(new Person("tq",43));

  52.                 Iterator it = ts.iterator();
  53.                 while(it.hasNext()){
  54.                         Person p = (Person)it.next();
  55.                         System.out.println(p.getName()+"…"+p.getAge());
  56.                 }
  57.         }
  58. }
复制代码
您需要登录后才可以回帖 登录 | 加入黑马