0

The following code throws a ClassCastException when I try to get a mapping with my custom Dog class as the key:

import java.util.TreeMap;

public class testMain {
        public static void main(String[] args) {

            TreeMap<Dog, String> m = new TreeMap<Dog, String>();
            m.put(new Dog("Fido"), "woof");

            // this line produces a ClassCastException
            String sound = m.get(new Dog("Fido"));

            System.out.println(sound);
    }
}

The dog class is simply:

public class Dog {

    String name;

    public Dog(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

I don't see why TreeMap would be casting the Dog class in the first place. Why do I get a ClassCastException when using a custom made class as the key? Any ideas on how to fix this code would be appreciated as well!

4

3 回答 3

4

TreeMap 根据键的顺序在插入时对元素进行排序。因此,用作键的对象必须实现Comparable接口。

请参阅我对您的Dog班级所做的修改。它现在有效:

public static class Dog implements Comparable<Dog> {

    String name;

    public Dog(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public int compareTo(Dog obj) {
        return name.compareTo(obj.name);
    }
}

编辑: ClassCastException 异常的原因:

如果您在方法Comparable<? super K> k = (Comparable<? super K>) key;的代码中看到该行,您将看到它正在尝试将您的密钥转换为对象。您的对象不是 instanceof 。getTreeMapComparableComparable

final Entry<K,V> getEntry(Object key) {
     // Offload comparator-based version for sake of performance
     if (comparator != null)
         return getEntryUsingComparator(key);
     if (key == null)
         throw new NullPointerException();
     Comparable<? super K> k = (Comparable<? super K>) key;
     Entry<K,V> p = root;
     while (p != null) {
         int cmp = k.compareTo(p.key);
         if (cmp < 0)
             p = p.left;
         else if (cmp > 0)
             p = p.right;
         else
             return p;
     }
     return null;
 }
于 2013-06-13T15:45:15.377 回答
1

如果你想在没有 Comparator 的 TreeMap 中将 Dog 用作键,Dog 必须实现 Comparable

于 2013-06-13T15:43:30.770 回答
0

你必须让你的 Dog 类实现Comparable接口。

class Dog implements Comparable<Dog>

从文档:

地图根据其键的自然顺序进行排序

于 2013-06-13T15:43:48.997 回答