ClassCastException when casting object Array to Long array

前端 未结 2 1851
无人共我
无人共我 2021-01-13 12:00

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

Exception in thread \"main\" java.lang.ClassCastException: [Ljava.lang.O

相关标签:
2条回答
  • 2021-01-13 12:12

    change

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

    to

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

    and let me know if it works :-)

    0 讨论(0)
  • 2021-01-13 12:23

    It's because Object[] Set.toArray() returns an object array. You can't downcast the array to a more specific type. Use <T> T[]Set.toArray(T[] a) instead. If the generic type method didn't exist you'd have to loop through each of the Objects in the return object array and cast each individually into a new Long array.

    0 讨论(0)
提交回复
热议问题