java程序,下图程序只能实现对集合元素中的名字排序,但怎么修改可以实现对年龄排序呢?
publicclasspersonimplementsComparable<person>{privateStringname;privateintage;publicS...
public class person implements Comparable<person> {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public person(String name, int age) {
this.name = name;
this.age = age;
}
public int compareTo(person p) {
int temp = this.age - this.age;
return temp==0?this.name.compareTo(p.name):temp;
}
}
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet<person> ts = new TreeSet<person>();
ts.add(new person("lisi8",20));
ts.add(new person("lisi5",23));
ts.add(new person("lisi",21));
ts.add(new person("lisi0",20));
Iterator<person> it = ts.iterator();
while(it.hasNext()){
person p = it.next();
System.out.println(p.getName()+":"+p.getAge());
}
}
} 展开
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public person(String name, int age) {
this.name = name;
this.age = age;
}
public int compareTo(person p) {
int temp = this.age - this.age;
return temp==0?this.name.compareTo(p.name):temp;
}
}
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet<person> ts = new TreeSet<person>();
ts.add(new person("lisi8",20));
ts.add(new person("lisi5",23));
ts.add(new person("lisi",21));
ts.add(new person("lisi0",20));
Iterator<person> it = ts.iterator();
while(it.hasNext()){
person p = it.next();
System.out.println(p.getName()+":"+p.getAge());
}
}
} 展开
展开全部
compareTo里面用年龄做判断就可以了。
更多追问追答
追问
改成这样还是不行
public int compareTo(person p) {
int temp = this.getName().compareTo(p.getName());
return temp==0?this.getAge()-p.getAge():temp;
}
追答
你要做双重判断啊。,return temp==0?this.getAge()-p.getAge():temp;这代码有问题吧。你是不是想实现这样,如果名字相同就进行年龄排序?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询