将对象数组转换为长整型数组时出现ClassCastException异常

5

当我尝试将Object数组转换为Long数组时,出现了以下异常:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Long;

我的hotelRooms映射中的键是Long类型,为什么不能进行强制转换呢?有人知道如何解决吗?

public class ObjectArrayToLongArrayTest {

private Map<Long, String[]> hotelRooms;

public static void main(String[] args) {

    ObjectArrayToLongArrayTest objectArrayToLongArrayTest =
        new ObjectArrayToLongArrayTest();
    objectArrayToLongArrayTest.start();
    objectArrayToLongArrayTest.findByCriteria(null);

}

private void start() {
    hotelRooms = new HashMap<Long, String[]>();
    // TODO insert here some test data.

    hotelRooms.put(new Long(1), new String[] {
            "best resort", "rotterdam", "2", "y", "129", "12-12-2008",
            "11111111"
    });

    hotelRooms.put(new Long(2), new String[] {
            "hilton", "amsterdam", "4", "n", "350", "12-12-2009", "2222222"
    });

    hotelRooms.put(new Long(3), new String[] {
            "golden tulip", "amsterdam", "2", "n", "120", "12-09-2009",
            null
    });
}

public long[] findByCriteria(String[] criteria) {

    Long[] returnValues;

    System.out.println("key of the hotelRoom Map" + hotelRooms.keySet());
    if (criteria == null) {
        returnValues = (Long[]) hotelRooms.keySet().toArray();
    }

    return null;
}
}   

尽管这个问题是关于Java而不是C++,但我发现这个讨论很有帮助:http://www.parashift.com/c++-faq-lite/proper-inheritance.html#faq-21.4 - Jherico
2个回答

25

更改

returnValues = (Long[]) hotelRooms.keySet().toArray();
returnValues = hotelRooms.keySet().toArray(new Long[hotelRooms.size()]);

如果它有效,请让我知道 :-)


谢谢,它有效。在Java接口Set<E>的API中,我看到了这两个方法:(1) Object[] toArray()和(2) <T> T[] toArray(T[] a)。为什么第一个方法无法正常工作? - loudiyimo
第一个代码可以正常工作,但它返回一个通用对象数组,这不是你想要的! - moritz

7

这是因为Object[] Set.toArray()返回一个对象数组。你不能将数组向下转型为更具体的类型。应该使用<T> T[]Set.toArray(T[] a)代替。如果没有通用类型方法,你就必须循环遍历返回对象数组中的每个对象,并将每个对象单独强制转换为一个新的长整型数组。


你帮我省了很多麻烦:在找到这个宝石之前,我不得不搜索很多错误的答案。谢谢! - PP.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接