[英]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, ie without writing two summing methods for each type of Set? 我怎么能用泛型来做这个,即不为每种类型的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. 如何使用Generics作为单个方法编写上述两种方法。 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
. 如果有帮助, getScore()
方法存在于Foo
和Bar
类中。 Any ideas and suggestions are much appreciated. 任何想法和建议都非常感谢。 Thanx 感谢名单
Define a common interface, say Scorable
: 定义一个通用接口,比如Scorable
:
public interface Scorable {
int getScore();
}
And implement it with Foo
and Bar
: 并使用Foo
和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 : 然后,使用通配符定义一个可以接受任何类型Scorable
方法:
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
. 哪个可以接收Set<Foo>
或Set<Bar>
因为它们都实现了Scorable
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.