如何计算arrayList中的属性?

时间:2013-09-21 23:21:51

标签: java arraylist

所以我有一个arrayList

 Dog spot = new Dog("Spot", "Lab","Blonde", Tail.OTTER,"Yes", 50, 3);
 Dog buddy = new Dog("Buddy", "Pit Bull", "Black", Tail.DOCKED,"Yes", 60, 2);
 Dog mia = new Dog ("Mia", "Pug", "Brown", Tail.RING ,"No", 70, 4);

现在50,60和70是狗的重量。我想在没有写出冗长,非灵活的代码的情况下总结它们,例如:

int totalWeight = spot.weight + buddy.weight + mia.weight;

有办法吗?

2 个答案:

答案 0 :(得分:3)

int totalWeight = 0;
for (final Dog dog : dogs) {
    totalWeight += dog.getWeight();
}

答案 1 :(得分:2)

将每个对象放在列表中

List<Dog> dogs = new ArrayList<>();
dogs.add(spot);
dogs.add(buddy);
dogs.add(mia);

int result = 0;
for(Dog dog : dogs) {
 result += dog.getWeight(); 
}