所以我有一个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;
有办法吗?
答案 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();
}