本帖最后由 张向辉 于 2012-12-8 13:34 编辑
import java.util.*;
class TreeSetDemo
{
public static void main(String[] args)
{
//System.out.println("Hello World!");
TreeSet<Person> ts= new TreeSet<Person>();
ts.add(new Person("abc001",12));
ts.add(new Person("abc002",14));
ts.add(new Person("abc003",16));
ts.add(new Person("abc004",17));
Iterator t = ts.iterator();
while(t.hasNext())
{
Person per = (Person)t.next();//此处为什么还得进行强转才能编译通过啊,我如果不加Person,便不能通过?迷茫了
sop(per.getName());
}
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
class Person implements Comparable
{
String name;
int age;
Person(String name,int age)
{
this.name=name;
this.age=age;
}
public String getName()
{
return this.name;
}
public int compareTo(Object obj)
{
//return this.name.compareTo((Person)obj.name);
if(!(obj instanceof Person))
throw new RuntimeException();
Person p=(Person)obj;
if(this.age>p.age)
return 1;
if(this.age==p.age)
return this.name.compareTo(p.name);
return -1;
}
public int getAge()
{
return age;
}
}
-----------------------------------------------------------------------------------------------------------------------------------------------
Person per = (Person)t.next();//此处为什么还得进行强转才能编译通过啊,我如果不加Person,便不能通过?
不加Person的话得到是什么类型啊?
|