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

ArrayList<Object> how to differentiate objects added

问题同题。我有一个数组列表,我以对象的形式向其中添加收入或支出。这个循环会总结所有元素吗,有没有更好的方法:?

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

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

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

中实现该接口
interface BudgetValue {
    double getValue();
}

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

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

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

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

流方法对我来说更有意义,如果你有很多值要通过将其转换为并行流来求和,它可以很容易地进行多线程处理。

在极少数情况下 instanceof 是合理的,但根据经验,如果您发现自己在使用它,请先问问自己是否缺少接口。

我建议让您的 ExpensesIncomes 类 实现一个通用接口,例如 LineItem。现在,如果您使用带符号的值(收入为正值,费用为负值),您只需在 LineItem 的任何实现上调用 getValue() 并将其添加到您的 运行 总计中......不if/else 需要,不需要收集 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);
}