当我尝试将Object数组转换为Long数组时,我得到此异常。
线程“main”中的异常 java.lang.ClassCastException: [Ljava.lang.Object;无法施展 [Ljava.lang.Long;
我在hotelRooms地图中的密钥很长,为什么无法投射。有人知道如何解决这个问题。
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;
}
}
答案 0 :(得分:25)
变化
returnValues = (Long[]) hotelRooms.keySet().toArray();
到
returnValues = hotelRooms.keySet().toArray(new Long[hotelRooms.size()]);
让我知道它是否有效: - )
答案 1 :(得分:7)
这是因为Object[] Set.toArray()
返回一个对象数组。您无法将数组转发为更具体的类型。请改用<T> T[]Set.toArray(T[] a)
。如果泛型类型方法不存在,则必须循环遍历返回对象数组中的每个对象,并将每个对象逐个转换为新的Long数组。