将ArrayList转换为Object数组

时间:2012-06-25 10:27:09

标签: java data-structures

我有一个TicketBooking类型的List,我将其设置为responseObject。当我尝试获取列表并转换回TicketBooking类型时,它会抛出ClassCastException。这是我的代码

 List<TicketBooking> bookingDetailList = new ArrayList<TicketBooking>();
    bookingDetailList.add(booking);
    if(Utils.isNotNull(oldBooking)) 
        bookingDetailList.add(oldBooking);
    respObj.setObject(bookingDetailList);

从这个方法我返回respObj。

在调用方法

    List bookingList = new ArrayList();
    bookingList.add(Arrays.asList(respObj.getObject()));
    booking = (TicketBooking) bookingList.get(0);

抛出ClassCastException

请帮忙。

4 个答案:

答案 0 :(得分:0)

您需要在调用方法时创建TicketBooking列表。

你的代码

 List bookingList = new ArrayList();
 bookingList.add(Arrays.asList(respObj.getObject()));
 booking = (TicketBooking) bookingList.get(0);

应替换为

 List<TicketBooking> bookingList= new ArrayList<TicketBooking>();
 List list =  Arrays.asList(respObj.getObject());
 for(Object obj in list ){
    bookingList.add(obj);
    booking = bookingList.get(0);
 }

或以下将做同样的

   List bookingList = new ArrayList();
bookingList.addAll(Arrays.asList(respObj.getObject()));
booking = (TicketBooking) bookingList.get(0);

答案 1 :(得分:0)

Arrays.asList(respObj.getObject())

这个表达式返回一个List对象,当然抛出ClassCasException

你应该

List list =  Arrays.asList(respObj.getObject());
for(Object obj in list){
      bookingList.add(obj);
}

答案 2 :(得分:0)

add()替换为addAll()

List bookingList = new ArrayList();
bookingList.addAll(Arrays.asList(respObj.getObject()));

如果使用add,它会将其视为实例(类型为List),因此第一个元素的类型为List,然后您尝试将其转换为TicketBooking }

答案 3 :(得分:0)

List bookingList = new ArrayList();
bookingList.add(Arrays.asList(respObj.getObject()));//error is here
booking = (TicketBooking) bookingList.get(0);

我认为在bookingList中你添加了一个完整的List而不是一个TicketBooking对象。并且您期待TicketBooking对象。

您应该按照以下方式修改代码。

ArrayList<TicketBooking> bookingList= new ArrayList<TicketBooking>();
bookingList.addAll((ArrayList<TicketBooking>)respObj.getObject()); //Add all to add whole list
booking =  bookingList.get(0);