简体   繁体   English

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

[英]return object of a certain 'type' from array list

I have an order 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);       
}

It is extended by three subclasses 'NonProfitOrder', 'RegularOrder', and 'OverseasOrder' each of which only differ in the way they calculateBill(). 它由三个子类“ NonProfitOrder”,“ RegularOrder”和“ OverseasOrder”扩展,每个子类的区别仅在于它们的calculateBill()方式不同。

Then I have and OrderManger class 然后我有和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;     
}   
}

I believe that i have everything working correctly, except that I am having trouble with the printOrders(String type) which return a string of all orders of 'type' where 'type' is "Regular", "Overseas", or "NonProfit". 我相信我一切正常,但我在printOrders(String type)遇到麻烦时会返回所有'type'订单的字符串,其中'type'为“ Regular”,“ Overseas”或“ NonProfit” 。 My question would be what is the correct way to loop through and array list and only returning the objects of a given 'type'? 我的问题是循环遍历数组列表并仅返回给定“类型”的对象的正确方法是什么?

Simple solution here would be the following: 以下是简单的解决方案:

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();       
}

Then when you call the method: 然后,当您调用该方法时:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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