I have two different types of Sets that need to be iterated and one of the values of the objects of the set need to be summed. How can I do this with Generics, i.e without writing two summing methods for each type of Set?
private Double calculateFooScoreSum(final Set<Foo> fooScoreSet)
{
Double sum = 0.0;
for (final Foo score : fooScoreSet)
{
sum += score.getScore();
}
return sum;
}
private Double calculateBarScoreSum(final Set<Bar> barScoreSet)
{
Double sum = 0.0;
for (final Bar score : barScoreSet)
{
sum += score.getScore();
}
return sum;
}
How can I write the above two methods using Generics as a single method. Something Like:
private static Double calculateScoreSum(Set<?> scoreSet)
{
Double sum = 0.0;
for(Object scoreObj : scoreSet){
//Some casting magic
sum+=score.getScore();
}
return sum;
}
If it helps, getScore() method exists in both classes Foo and Bar.
Any ideas and suggestions are much appreciated.
Thanx
Define a common interface, say
Scorable:And implement it with
FooandBar:And then, define a method that can accept any kind of
Scorable, using wildcards:Which can receive either
Set<Foo>orSet<Bar>since they both implementScorable.