ArrayList <object>如何区分添加的对象</object>

时间:2015-01-18 23:06:45

标签: java arraylist

问题与标题中的问题相同。我有一个arraylist,我以对象的形式增加收入或支出。这个循环将总结所有元素,还有更好的方法:?

    public void sumOfAllExpAndIn(){
    int tmp = 0;
    for (Iterator<Object> it = database.iterator(); it.hasNext();){

        if (it.next() instanceof Expenses){
            Expenses excalc = new Expenses();
            excalc = (Expenses) it.next();
            tmp -= excalc.value;
        }
        else {
            incomes incalc =new incomes();
            incalc = (incomes) it.next();
            tmp += incalc.value;
        }
    }
    System.out.format("the overall balance is %d",tmp);
}

2 个答案:

答案 0 :(得分:2)

是的,有几种更好的方法。

首先,我建议您将其声明为对象列表。更好的方法是声明一个接口,然后在每个类中实现接口:

interface BudgetValue {
    double getValue();
}

class Expense implements BudgetValue {
    public double getValue() {
        return -value;
    }
}

class Income implements BudgetValue {
    public double getValue() {
        return +value;
    }
}

然后您可以声明BudgetValues列表而不是Objects作为方法的输入:

double sumBudgetValues(List<BudgetValues> budgetValues) {
}

有两种简单的方法可以总结它们:

double total = 0.0;
for (BudgetValue value: budgetValues) {
    total += value.getValue();
}
return total;

或使用Java 8:

return budgetValues.stream()
    .mapToDouble(BudgetValue::getValue)
    .sum().orElse(0.0);

对于我来说,stream方法对我来说更有意义,并且如果通过将其转换为并行流来获得大量值,则可以轻松实现多线程。

有一些罕见的场合,instanceof是合理的,但根据经验,如果你发现自己使用它,那么首先问问自己是否缺少界面。

答案 1 :(得分:0)

我建议您的ExpensesIncomes类实现一个通用接口,例如LineItem。现在,如果您使用签名值(收入为正数而费用为负数),您只需在getValue()的任何实施中调用LineItem并将其添加到您的运行总计中...如果需要/否则,不需要Object的集合。

public void sumOfAllExpAndIn(){
  int tmp = 0;
  for (Iterator<LineItem> it = database.iterator(); it.hasNext();){
      tmp += it.next().getValue();
    }
  }
  System.out.format("the overall balance is %d",tmp);
}