有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用自定义类作为键时使用Java的TreeMap强制转换ClassCastException

当我试图以自定义Dog类作为键获取映射时,以下代码抛出一个ClassCastException

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);
    }
}

狗的种类很简单:

public class Dog {

    String name;

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

    public String getName() {
        return name;
    }
}

我不明白为什么TreeMap首先会选Dog当使用定制类作为密钥时,为什么会出现ClassCastException任何关于如何修复此代码的想法都将不胜感激


共 (3) 个答案

  1. # 1 楼答案

    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异常的原因:

    如果在TreeMapget方法的代码中看到Comparable<? super K> k = (Comparable<? super K>) key;行,您将看到它正试图将密钥强制转换到Comparable对象。您的对象不是Comparable的实例

    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;
     }
    
  2. # 2 楼答案

    如果你想在没有比较器的树形图中将其用作键,Dog必须实现Comparable

  3. # 3 楼答案

    你必须让你的狗类实现Comparable接口

    class Dog implements Comparable<Dog>
    

    从文件中:

    The map is sorted according to the natural ordering of its keys