本帖最后由 耿渊博 于 2014-4-2 21:43 编辑
用TreeSet添加对象去重复,怎么不对啊? 下面是代码- package com.Iterator;
- import java.util.*;
- //定义学生类
- class Student implements Comparable{
- String name;
- int age;
- Student(String name,int age ) {
- this.age = age;
- this.name = name;
- }
- public String getName() {
- return name;
- }
- public int getAge() {
- return age;
- }
- //复写compareTo
- public int compareTo(Object obj){
- if(!(obj instanceof Student))
- throw new RuntimeException("不是学生对象");
- Student stu = (Student)obj;
-
- if(this.age>stu.age)
- return 1;
- if(this.age == stu.age)
- return 0;
- return -1;
- }
-
-
-
- }
- public class TreeSetDemo {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
-
- TreeSet ts = new TreeSet();
- //添加元素
- ts.add(new Student("lisi01",15));
- ts.add(new Student("lisi01",17));
- ts.add(new Student("lisi03",15));
- ts.add(new Student("lisi02",18));
-
- //定义迭代器
- Iterator it = ts.iterator();
-
- while(it.hasNext()){
- Student stu = (Student)it.next();
- sop(stu.getName()+"....."+stu.getAge());
- }
-
- }
- public static void sop(Object obj){
- System.out.println(obj);
- }
- }
复制代码
|