I currently have the following method in a class which I hope I can push to a superclass since I will have a few other classes which will need similar functionality.
public long convertToLong(EnumSet<SomeTypeHere> es) {
long a = 0;
for(SomeTypeHere sth : es) {
a += sth.someLongProperty();
}
}
It would be great if I can do this, I've never really used java generics before other than with collections.
You will need to put a bound on the generic type. If the class which contains convertToLong is parameterized on the same type, you can put the bound there:
import java.util.*;
public class GenericTest<C extends GenericTest.HasLongProperty> {
static interface HasLongProperty {
long someLongProperty();
}
public long convertToLong(Collection<C> es) {
long a = 0;
for(C sth : es)
a += sth.someLongProperty();
return a;
}
}
Or if the class which contains convertToLong is not generic, you can put the bound in the declaration of that one method alone:
import java.util.*;
public class GenericTest {
static interface HasLongProperty {
long someLongProperty();
}
public <C extends GenericTest.HasLongProperty> long convertToLong(Collection<C> es) {
long a = 0;
for(C sth : es)
a += sth.someLongProperty();
return a;
}
}
I think you want something like this:
public <T extends SomeType> long convertToLong(Collection<T> es) {
long a = 0;
for(T sth : es) {
a += sth.someLongProperty();
}
return a;
}
This says that you can pass in a Set of type T where T can be any subclass of SomeType and SomeType has the function someLongProperty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With