该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
马克-to-win:前面讲过进入TreeSet的每个元素是都排了序的,如果被添加的元素是我们自己定义的,就需要告诉TreeSet排序的规则,这个规则就要在Comparable中定义。在下面的例子中,当我们要往TreeSet中添加我们自己定义的类Worker对象时,就在compareTo中定义排序规则。
例:3.5.1
/*why in the past never implements Comparable? becasue Integer claas and
String class both implements this Comparable.
java.lang.Object
java.lang.String
All Implemented Interfaces:
CharSequence, Comparable, Serializable
*/
import java.util.*;
//Comparable接口在java.lang包中定义
//定义的方法:
//int compareTo(Object o);
//实现该接口就可以实现按用户定义的自然顺序排列对象。
/*you must implements Comparable,otherwise, when you add the second element into
the treeset, it will report error, because it will search for Comparable
interface. */
class Worker implements Comparable {
int workNum;
String name;
int money;
public Worker(int workNum, String name, int money) {
this.workNum = workNum;
this.name = name;
this.money = money;
}
// 按姓名排序,如果姓名同,再按工资排
/* public int compareTo(Object o) { Worker e = (Worker) o; int cmp =
name.compareTo(e.name); return (cmp != 0 ? cmp : money - e.money); }*/
。。。。。。。。。。。。。。。。。
详情黏贴以下网址在地址栏后请进:http://www.mark-to-win.com/JavaBeginner/JavaBeginner7_web.html#DefinitionUsageOfComparable