import java.util.*;class Student implements Comparable<Student>
{
private String name;
private int age;
Student(String name,int age)
{
this.name=name;
this.age=age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public int compareTo(Student obj)
{
if(!(obj instanceof Student))
throw new RuntimeException();
Student stu=obj;
if(this.age>stu.age)
return 1;
else if(this.age<stu.age)
return -1;
else
return this.name.compareTo(stu.name);
}
}class Demo2
{
public static void main(String[] args) 
{
Student stu1 = new Student("zhangsan",20);
Student stu2 = new Student("zhangsan",22);
Student stu3 = new Student("lisi",20);
Student stu4 = new Student("wangwu",25);
MyCompare m = new MyCompare();
TreeSet<Student> t = new TreeSet<Student>(m);
t.add(stu1);
t.add(stu2);
t.add(stu3);
t.add(stu4);
//show(t);
Iterator<Student> i = t.iterator();
Student s;
while(i.hasNext())
{
s=i.next();
System.out.println(s.getName()+"----"+s.getAge());
}
}
/*public static void show(TreeSet t)
{
Iterator<Student> i = t.iterator();
Student s;
while(i.hasNext())
{
s=i.next();
System.out.println(s.getName()+"----"+s.getAge());
}
}*/
}class MyCompare implements Comparator<Student>
{
public int compare(Student obj1,Student obj2)
{
return obj1.getName().compareTo(obj2.getName());
}
}
如果这么写就没错
但是把show函数打开就产生警告怎么回事,已经写了Iterator<Student> i = t.iterator();
为什么还会产生这样的警告 注: Demo2.java使用了未经检查或不安全的操作。
注: 有关详细信息, 请使用 -Xlint:unchecked 重新编译。iteratorjava