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

© liwei92244256 中级黑马   /  2014-9-19 13:09  /  825 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

下面列出代码:
import java.util.*;
class Student //implements Comparable<Student>
{
        private String name;
        private int age;
        private String address;
        Student (String name,int age)
        {
                this.name=name;
                this.age=age;
        }
        public String getName()
        {
                return name;
        }
/*        public int compareTo(Student obj)
        {
                int num=this.name.compareTo(s.name);
                if(num==0)
                {
                        return new Integer(this.age).compareTo(new Integer(s.age));
                }                 
                return num;
        }
        */
        public int getAge()
        {
                return age;
        }
        public String getAddress()
        {
                return address;
        }
       
//        private String address;
}
class com implements Comparator<Student>
{
        public int compare(Student s1,Student s2)
        {               
        //        System.out.println(s1.getName()+"--"+s2.getName());
                int num=s1.getName().compareTo(s2.getName());
                if(num==0)
                {
                        return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
                }                 
                return 1;
        }
}
class MapDemo
{
        public static void main(String args[])
        {
                TreeSet<Student> t=new TreeSet<Student>(new com());
       
                t.add(new Student("liwei",24));
                t.add(new Student("liwei",24));
                t.add(new Student("zhangweidsfa",20));
                t.add(new Student("liwe",24));
                t.add(new Student("zhangweidsfa",20));
                t.add(new Student("liwei",24));
                show(t);
                //保证student的唯一性。
            HashMap<Student,String> h=new HashMap<Student,String>();
                //h.put();

        }
        public static void show(TreeSet<Student> t)
        {
                Iterator<Student> it=t.iterator();
                while (it.hasNext())
                {
                        Student  s=it.next();
                        System.out.println(s.getName()+"--"+s.getAge());
                }
                 
        }
}
问题: 添加的新元素,最后一个元素和第一个元素相同,都可以输出,输出两次相同。其他的只输出一个

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马