[Solved] How to add the value of all the objects?

[ad_1]

In rare cases the thing that you want could be reasonably, but normally the class is not aware of all it’s elements. A total Score is for a Collection of Score elements, maybe a List or a Set.

So you would do:

class Score {
  int value;
  // ...
  public static int totalScore(Collection<Score> scores){ 
    int sum = 0;
    for (Score s: scores){
      sum += s.value;
    }
    return sum;
  }
}

And outside you would have

List<Score> myBagForScores = new ArrayList<>();
Score e1 = new Score...
myBagForScores.add(e1);
// e2, e3 and so on
int sum = Score.totalScore(myBagForScores);

Hope that helps!

[ad_2]

solved How to add the value of all the objects?