关于Comparator构造TreeSet的问题。谢谢各位大侠!!! 定义一个类Person,含有两个属性姓名(name,String),年龄(age,int),要求构造方法带参数并初始化两个属性,重写toString方法打印两个属性的值。定义一个TreeSet,添加5个Person类的对象到该TreeSet,并按照属性name的字典排列顺序在TreeSet中排列这5个Person类的对象。 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 来看看这篇Blog吧,能帮上一点忙:Java中的排序(一) import java.util.*;public class Person implements Comparable { private String name; private int age; Person() { } Person(String name, int age) { this.name = name; this.age = age; } public String toString() { return "[name:"+this.name + " age:" + age + "]"; } public int compareTo(Object o) { Person p = (Person)o; return this.name.compareTo(p.name); } public static void main(String[] args) { TreeSet<Person> ts = new TreeSet<Person>(); ts.add(new Person("zeng",20)); ts.add(new Person("cheng",21)); ts.add(new Person("hang",19)); ts.add(new Person("ceng",25)); ts.add(new Person("wang",21)); for(Person p:ts) { System.out.println(p); } } Java 的困惑 郁闷,求高手解惑!swt打包后,hibernate无法使用 JAVA可以处理GIF动画吗 对于初学者,JSP那本书比较好? ProgressBar中进度条中显示进度百分比字体重影的现象 谁来帮帮我bean 客户端文件上传到服务器保存在数据库中 怎么实现啊? 安装了JBuilder8,什么都不会,哪有教程可以看啊? ldap分页查询,SizeLimitExceededException 简单socket编程,谁能告诉我这是怎么回事? 在JAVA项目中怎么显示条形图 如何使用给定路径读取文件。
import java.util.*;
public class Person implements Comparable {
private String name;
private int age;
Person() {
}
Person(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "[name:"+this.name + " age:" + age + "]";
}
public int compareTo(Object o) {
Person p = (Person)o;
return this.name.compareTo(p.name);
}
public static void main(String[] args) {
TreeSet<Person> ts = new TreeSet<Person>();
ts.add(new Person("zeng",20));
ts.add(new Person("cheng",21));
ts.add(new Person("hang",19));
ts.add(new Person("ceng",25));
ts.add(new Person("wang",21));
for(Person p:ts) {
System.out.println(p);
}
}