一直搞不清楚,这方法靠什么来排的序,仅仅只是依靠返回 -1、0、1来排。这要怎么排呢??搞了段代码,随便看看:
public int compareTo(TreeType arg) {
return (arg.i < i ? -1 : (arg.i == i ? 0 : 1));
}
public int compareTo(TreeType arg) {
return (arg.i < i ? -1 : (arg.i == i ? 0 : 1));
}
test ? 语句1 : 语句2语句1当 test 是 true 时执行的语句。语句2当 test 是 false 时执行的语句。
public int compareTo(TreeType arg)
每次执行该方法,我只需要判断参数arg和this.arg 两个对象之间的大小关系.
排9个元素会在循环中多次调用这个方法.
return (arg.i < i ? -1 : (arg.i == i ? 0 : 1));
}
if (arg.i < i) {
return -1;
} else {
if (arg.i == i) {
return 0; } else {
return 1;
}
}
这样好理解了吗
你问怎样排序,那就看你用什么排序算法或者说用什么类,你如果用Collections.sort,里面用的是类似快速排序的算法进行的排序算法你应该另外去看相关的文档
import java.util.*;class SetType {
int i;
public SetType(int n) { i = n; }
public boolean equals(Object o) {
return o instanceof SetType && (i == ((SetType)o).i);
}
public String toString() { return Integer.toString(i); }
}class TreeType extends SetType
implements Comparable<TreeType> {
public TreeType(int n) { super(n); }
public int compareTo(TreeType arg) {
return (arg.i < i ? -1 : (arg.i == i ? 0 : 1));
}
}public class TypesForSets {
static <T> Set<T> fill(Set<T> set, Class<T> type) {
try {
for(int i = 0; i < 10; i++)
set.add(
type.getConstructor(int.class).newInstance(i));
} catch(Exception e) {
throw new RuntimeException(e);
}
return set;
}
static <T> void test(Set<T> set, Class<T> type) {
fill(set, type);
fill(set, type); // Try to add duplicates
fill(set, type);
System.out.println(set);
}
public static void main(String[] args) {
test(new TreeSet<TreeType>(), TreeType.class); }
}
TreeSet 是一个有排序功能的集合, 它可以存放各种各样的对象。但,每种的对象的比较规则都不一样,那么,该怎样比较对象的大小呢?最好的办法就是让每个类定义自己的比较规则(即compareTo方法),当向TreeSet 加入一个对象时就调用它的 compareTo()方法和其他对象比较,以找到它应该存放的位置。
调用
public TreeSet() {
this(new TreeMap<E,Object>());
}
调用add方法
public boolean add(E o) {
return m.put(o, PRESENT)==null;
}
调用put方法
调用compare方法
调用compareTo方法,比较.
class ByChangDu implements Comparable{
private String Chuan;
public ByChangDu(String zifu){
Chuan=zifu;
}
public int compareTo(Object o){
ByChangDu it=(ByChangDu)o;
return this.Chuan.length()-it.Chuan.length();
//return this.Chuan.compareTo(it.Chuan);
}
public String toString(){
return Chuan;
}
}//新曙光
public class ByChangDuDemo{
public static void main(String args[]){
ByChangDu YiZuChuan[]={new ByChangDu("abc"),
new ByChangDu("xy"),
new ByChangDu("xinshuguang"),
new ByChangDu("www."),
new ByChangDu("12")
};
Arrays.sort(YiZuChuan);
for(int i=0;i<YiZuChuan.length;i++){
System.out.println(YiZuChuan[i]);
}
}
}//www.xinshuguang.org
本程序视频讲解