从数组列表中返回某个“类型”的对象

时间:2013-09-19 16:34:02

标签: java loops arraylist abstract-class

我有一个订单类:

public abstract class Order {
protected String location;
protected double price;

public Order(double price, String location){
    this.price = price;
    this.location = location;
}
public abstract double calculateBill();

public String getLocation() {
    return location;
}
public double getPrice() {
    return price;
}
public abstract String printOrder(String format);       
}

它由三个子类'NonProfitOrder','RegularOrder'和'OverseasOrder'扩展,每个子类只有它们计算比尔()的方式不同。

然后我有和OrderManger类

public class OrderManager {
private ArrayList<Order> orders;

public OrderManager() {

}
public OrderManager(ArrayList<Order> orders) {
    this.orders = orders;   
}   
public void addOrder(Order o) {
    orders.add(o);
}   
public ArrayList<Order> getOrdersAbove(double val) {
    for (Order o : orders) {
        double bill = o.calculateBill();
        if (bill > val)
            orders.add(o);
    }
    return orders;
}   
public int numOrders() {
    return orders.size();
}   
public String printOrders() {
    for (Order o : orders){
        String format = "Long";
    }
    return printOrders("Long");
}
public String printOrders(String type) {
    for (Order o : orders) {

    }       
}
public double totalBill() {
    double sum = 0;
    for(Order o : orders) {
         sum = o.calculateBill();
    }
    return sum;     
}   
}

我相信我一切正常,除了我遇到printOrders(字符串类型)的问题,它返回所有'type'命令的字符串,其中'type'是“Regular”,“Overseas”,或者“非营利性”。我的问题是循环和数组列表的正确方法是什么,只返回给定'类型'的对象?

1 个答案:

答案 0 :(得分:1)

这里的简单解决方案如下:

public String printOrders(Class orderClass) {
    StringBuilder sb = new StringBuilder();
    for (Order o : orders) {
        if(o.getClass().equals(orderClass))
        {
            sb.append(o.printOrder()).append("\n");
        }
    }
    return sb.toString();       
}

然后当你调用方法时:

String orderString = orderManager.printOrders(NonProfitOrder.class);
System.out.println(orderString);