本帖最后由 白堇翎 于 2013-3-14 17:14 编辑
Set接口本身就是为了存储不重复的元素而存在的
假如你一定要用Set接口的话..
那可以给每个人加一个身份证号码 就可以实现这种功能了- package Test;
- import java.util.Iterator;
- import java.util.TreeSet;
- public class IDDemo {
- public static void main(String[] args) {
- TreeSet ts = new TreeSet();
- ts.add(new Student("lisi02", 22, 1001));// 建立对象,并传入参数
- ts.add(new Student("lisi007", 20, 1002));
- ts.add(new Student("lisi09", 19, 1003));
- ts.add(new Student("lisi01", 19, 1004));
- ts.add(new Student("lisi01", 19, 1005));// 年龄和姓名与上面的相同,视为同一个人,无法存入并输出
- Iterator it = ts.iterator();
- while (it.hasNext()) {
- Student stu = (Student) it.next();
- System.out.println(stu.getName() + "..." + stu.getAge() + "...."
- + stu.getID());
- }
- }
- }
- class Student implements Comparable // 该接口强制让学生具备比较性
- {
- private String name;
- private int age;
- private int ID;
- Student() {
- super();
- }
- Student(String name, int age, int ID) {
- super();
- this.name = name;
- this.age = age;
- this.ID = ID;
- }
- public int compareTo(Object obj) {
- if (!(obj instanceof Student))
- throw new RuntimeException("不是学生对象");
- Student s = (Student) obj;
- System.out.println(this.name + "...compareto..." + s.name);// 输出比较过程
- if ( this.age > s.age)
- return 1;
- if ((this.ID == s.ID) && (this.age == s.age))// 当年龄相同时,按照姓名排序
- {
- return this.name.compareTo(s.name);
- }
- return -1;
- }
- public void setName(String name) {
- this.name = name;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public void setID(int ID) {
- this.ID = ID;
- }
- public String getName() {
- return name;
- }
- public int getAge() {
- return age;
- }
- public int getID() {
- return ID;
- }
- }
复制代码 这是修改后的代码 |