[ACCEPTED]-ClassCastException when casting object Array to Long array-java

Accepted answer
Score: 25


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


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

and let me know if it works :-)


Score: 7

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

More Related questions