将对象Array转换为Long数组时出现ClassCastException [英] ClassCastException when casting object Array to Long array

查看:113
本文介绍了将对象Array转换为Long数组时出现ClassCastException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试将Object数组转换为Long数组时,我得到此异常。

I get this exception when i try to cast an Object array to a Long array.


线程main中的异常
java.lang.ClassCastException:
[Ljava.lang.Object;不能转换为
[Ljava.lang.Long;

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

我在hotelRooms地图中的密钥很长,为什么是不可能施展。有人知道如何解决这个问题。

My keys in my hotelRooms map are Long, why it is not possible to cast. Does someone know how to solve this.

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


推荐答案

更改

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

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

让我知道它是否有效: - )

and let me know if it works :-)

这篇关于将对象Array转换为Long数组时出现ClassCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆