无法使用对象集合将hashset转换为treeset

时间:2015-10-13 15:47:00

标签: java collections set hashset treeset

我必须将Hashset转换为TreeSet,但我有错误

// Here, All is ok, Chien is an object.
Set<Chien> animaux = new HashSet<Chien>();
animaux.add(new Chien("non", 10));
animaux.add(new Chien("zoz", 15));
animaux.add(new Chien("non", 10));

// And then i have to convert it to TreeSet 
// IntellJ-Idead says me that's ok...
// But i have an error here
TreeSet<Chien> treseet = new TreeSet<Chien>(animaux);

但是当我尝试编译时:

Exception in thread "main" java.lang.ClassCastException: fr.univtln.arouani277.vertebre.animal.Chien cannot be cast to java.lang.Comparable
    at java.util.TreeMap.put(TreeMap.java:559)
    at java.util.TreeSet.add(TreeSet.java:255)
    at java.util.AbstractCollection.addAll(AbstractCollection.java:322)
    at java.util.TreeSet.addAll(TreeSet.java:312)
    at java.util.TreeSet.<init>(TreeSet.java:160)
    at fr.univtln.arouani277.App.main(App.java:40)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:622)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

以下是我的文件Chien

public class Chien extends Mammifere implements Ibruit {
    public Chien(String pnom, int page) {
        super(pnom, page);
    }

    public void aboyer() {
        System.out.println("ouaf");
    }

    public void crier() {
        System.out.println("ouaf");
    }
}

它扩展了Mammifere

public abstract class Mammifere extends Animal {
    public Mammifere(String pnom, int page) {
        super(pnom, page);
    }
}

扩展Animal

public abstract class Animal extends Vertebre {
    public Animal(String nom, int page) {
        super(nom, page);
    }

    public void aboyer() {
    }

    public String toString() {
        System.out.println("Je suis un animal");
        return super.toString();
    }
}

扩展Vertebrehttp://pastebin.com/Aa4Rw8sW

2 个答案:

答案 0 :(得分:6)

HashSet不同,TreeSet依赖于排序,因此可以快速确定是否存在重复。当您将HashSet传递给TreeSet constructor时,会发现您的Chien个对象不是Comparable

  

构造一个新的树集,其中包含指定集合中的元素,并根据其元素的自然顺序进行排序。插入到集合中的所有元素都必须实现Comparable接口。此外,所有这些元素必须是可相互比较的:e1.compareTo(e2)不得为集合中的任何元素e1和e2抛出ClassCastException。

您有两个选择:

答案 1 :(得分:2)

错误告诉你出了什么问题:

  

ClassCastException:fr.univtln.arouani277.vertebre.animal.Chien无法强制转换为java.lang.Comparable

您应该让您的课程Chien实施Comparable。这在TreeSet(强调我的)的构造函数中有记录:

  

构造一个新的树集,其中包含指定集合中的元素,并根据其元素的自然顺序进行排序。 插入到集合中的所有元素都必须实现Comparable接口。此外,所有这些元素必须是可相互比较的:e1.compareTo(e2)不得为集合中的任何元素e1和e2抛出ClassCastException。

这是预期的,因为TreeSet命令其元素,因此它必须知道如何比较它们。

由于您正在构建复杂的类层次结构,因此Comparable接口应该由顶级类Vertebre实现。这取决于您希望如何进行比较。