下面列出代码:
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());
}
}
}
问题: 添加的新元素,最后一个元素和第一个元素相同,都可以输出,输出两次相同。其他的只输出一个
|
|