import java.util.*;
class Students implements Comparable
{
private String name;
private int age;
Students(String name,int age)
{
this.name = name;
this.age = age;
}
public int compareTo(Object obj)
{
if(!(obj instanceof Students))
throw new RuntimeException("你不是学生");
Students s = (Students)obj;
if(this.age>s.age)
return 1;
if(this.age==s.age)//如果比较的年龄相同就返回0 意思就是 比较的年龄相同 只存一个进来
{
return this.name.compareTo(s.name);
}
return -1;
}
public int getAge()
{
return age;
}
public String getName()
{
return name;
}
}
public class Test1
{
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args)
{
TreeSet ts = new TreeSet(new MyCompare());
//比如的是姓名排序
ts.add(new Students("lisi02",22));
ts.add(new Students("lisi007",20));
ts.add(new Students("lisi09",19));
ts.add(new Students("lisi06",18));
ts.add(new Students("lisi007",29));
Iterator it = ts.iterator();
while(it.hasNext())
{
Students stu = (Students)it.next();
sop(stu.getName()+"..."+stu.getAge());
}
}
}
class MyCompare implements Comparator//比较的是姓名排序
{
public int compare(Object o1,Object o2)
{
Students s1 = (Students)o1;
Students s2 = (Students)o2;
int num = s1.getName().compareTo(s2.getName());
if(num == 0)//容易理解的if方法
{
return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
}
return num;
}
}
经过运行正确,你下面的Mycompare中的函数Student应该写成Students,可以直接用泛型,下面是试用泛型的代码
import java.util.*;
class Students implements Comparable
{
private String name;
private int age;
Students(String name,int age)
{
this.name = name;
this.age = age;
}
public int compareTo(Object obj)
{
if(!(obj instanceof Students))
throw new RuntimeException("你不是学生");
Students s = (Students)obj;
if(this.age>s.age)
return 1;
if(this.age==s.age)//如果比较的年龄相同就返回0 意思就是 比较的年龄相同 只存一个进来
{
return this.name.compareTo(s.name);
}
return -1;
}
public int getAge()
{
return age;
}
public String getName()
{
return name;
}
}
public class Test1
{
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args)
{
TreeSet<Students> ts = new TreeSet<Students>(new MyCompare());
//比如的是姓名排序
ts.add(new Students("lisi02",22));
ts.add(new Students("lisi007",20));
ts.add(new Students("lisi09",19));
ts.add(new Students("lisi06",18));
ts.add(new Students("lisi007",29));
Iterator<Students> it = ts.iterator();
while(it.hasNext())
{
Students stu = (Students)it.next();
sop(stu.getName()+"..."+stu.getAge());
}
}
}
class MyCompare implements Comparator<Students>//比较的是姓名排序
{
public int compare(Students s1,Students s2)
{
// Students s1 = (Students)o1;
// Students s2 = (Students)o2;
int num = s1.getName().compareTo(s2.getName());
if(num == 0)//容易理解的if方法
{
return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
}
return num;
}
}
|