简体   繁体   中英

Java - how to iterate / traverse nested list of objects?

I'd like to iterate over a nested list of objects. reservedOrder is a list of objects containing a list of PlannedOrder.

public class PlannedOrder {
      private Object name;
      private Object price;
      private Object quantity;      
}

final List<Object> reservedOrders = new ArrayList<Object>();
for (final Iterator iterator = AllOrdersList.iterator(); iterator.hasNext();)
    {
    if(condition){
      final OrderModel orderModel = (OrderModel) iterator.next();   
      final List<PlannedOrder> plannedOrders = new ArrayList<PlannedOrder>();
      final PlannedOrder singleOrder = new PlannedReservationOrder();
      singleOrder.setName(orderModel.getName());
      singleOrder.setPrice(orderModel.getPrice());
      singleOrder.setQuantity(orderModel.getQuantity());
      reservedOrders.addAll(plannedOrders);
      }
    }

Can someone explain why java.lang.ClassCastException is thrown here in this nested loop? How can I access each object in the inner list with for-each / iterator?

for (final Object order : reservedOrders)
    {
     final List<PlannedOrder> singleOrder = (List<PlannedOrder>) order;
        for (final PlannedOrder plannedReservationOrder : singleOrder)
            {
              // java.lang.ClassCastException is thrown here $PlannedOrder cannot be cast to java.util.ArrayList

I think your problem is this line:

reservedOrders.addAll(plannedOrders);

It seems that you're expecting the plannedOrders list itself to be added to the reservedOrders list. But that's not what this does. This adds each element IN plannedOrders to the reservedOrders list. I think what you want instead is:

reservedOrders.add(plannedOrders);

This will cause the plannedOrders list to be added to the reservedOrders list, giving you the nested structure that you're expecting.

Why are you not properly defining the type of objects that are contained in reservedOrders ? If you did this, the compiler would then catch this error and so you wouldn't need to wait for a runtime error. I think what you want is:

final List<List<PlannedOrder>> reservedOrders = new ArrayList<>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM