本帖最后由 了无尘 于 2012-4-17 20:26 编辑
你这个 compareTo方法始终返回0.即视为所有的对象都相等,所以你这个集合只能放一个对象。。。。
下边这个是我写的一个按照单词自然顺序排列的一个例子,- import java.util.TreeSet;
- class Drink implements Comparable
- {
-
- public String name;
-
- public Drink(String name)
- {
-
- this.name = name;
- }
-
- // 根据英语单词的自然顺序做比较
- public int compareTo(Object o)
- {
-
- char[] a = name.toCharArray(), b = ((Drink) o).name.toCharArray();
-
- int index = 0;
-
- while (a[index] == b[index])
- {
- if (index == a.length - 1 && index < b.length - 1)
- {
- return -1;
- }
- else if (index == b.length - 1 && index < a.length - 1)
- {
- return 1;
- }
- index++;
- if(index == a.length && index == b.length)
- {
- return 0;
- }
- }
-
- return a[index] - b[index];
- }
-
- }
- public class A
- {
-
- public static void main(String[] args)
- {
-
- TreeSet set = new TreeSet();
- System.out.println(set.add(new Drink("Coffee")));
- System.out.println(set.size());
- System.out.println(set.add(new Drink("Coffeea")));
- System.out.println(set.size());
- System.out.println(set.add(new Drink("Tea")));
- System.out.println(set.size());
- System.out.println(set.add(new Drink("Water")));
- System.out.println(set.size());
- System.out.println(set.add(new Drink("Cappuccino")));
- System.out.println(set.size());
- System.out.println(set.add(new Drink("Xo")));
- System.out.println(set.size());
- System.out.println(set.add(new Drink("Xo")));
- System.out.println(set.size());
- System.out.println(set.add(new Drink("Champagne")));
- System.out.println(set.size());
- for (Object d : set.toArray())
- {
- System.out.println(((Drink) d).name);
- }
- }
- }
复制代码 |