Panshul
Panshul

Reputation: 1084

Casting Generic types in loops Java 7

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

Upvotes: 3

Views: 288

Answers (1)

Jo&#227;o Silva
Jo&#227;o Silva

Reputation: 91349

Define a common interface, say Scorable:

public interface Scorable {
  int getScore();
}

And implement it with Foo and Bar:

public class Foo implements Scorable {
  public int getScore () { return 1; }
}

public class Bar implements Scorable {
  public int getScore () { return 2; }    
}

And then, define a method that can accept any kind of Scorable, using wildcards:

private static Double calculateScoreSum(Set<? extends Scorable> scoreSet) {
    Double sum = 0.0;
    for (Scorable score : scoreSet){
        sum += score.getScore();
    }
    return sum;
}

Which can receive either Set<Foo> or Set<Bar> since they both implement Scorable.

Upvotes: 5

Related Questions