5

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.Object; cannot be cast to [Ljava.lang.Long;

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

2 Answers 2

25

change

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

to

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

and let me know if it works :-)

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, it works. In the java api of Interface Set<E>. I see these two methods (1) Object[] toArray() and (2) <T> T[] toArray(T[] a). Why does the first method not work.
the first one works just fine, but it returns an array of generic objects, which is not what you want!
7

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.

1 Comment

You saved me a lot of trouble: I had to do a lot of searching through incorrect answers before I found this gem. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.