I know this topic has been discussed quiet a while for now (e.g, Java generics warnings on java.util.Collections, java generics, unchecked warnings, etc) but I am facing a situation for which I cannot find an explanation.
I have a Predicate class defined as
public interface Predicate<T> {
boolean holds(T o) ;
}
Then, I have a utility class (PredicateUtils) to compose predicates. An example method in there is
public static <T> Predicate join(final Predicate<T> p1, final Predicate<T> p2) {
return new Predicate<T>() {
@Override
public boolean holds(T o) {
return (p1.holds(o) && p2.holds(o)) ;
}
} ;
}
However, when I call a join method, for instance, passing two Predicate instances, I get the following error from the jdk (javac 1.7.0_51) compiler:
warning: [unchecked] unchecked conversion
return PredicateUtils.join(p1, p2)
required: Predicate<Integer>
found: Predicate
To simplify the discussion, once can define the method bellow (dummy code) in a given class:
public static Predicate<Integer> test() {
Predicate<Integer> p1 = new Predicate<Integer>() {
public boolean holds(Integer o) { return true ; }
};
Predicate<Integer> p2 = new Predicate<Integer>() {
public boolean holds(Integer o) { return true ; }
};
return join(p1, p2) ;
}
and will see that upon the compilation of the associated class, javac issues the same warning.
Notice the return type of your join
method:
public static <T> Predicate join(final Predicate<T> p1, final Predicate<T> p2)
You're using raw type, and hence that warning. Change it to:
public static <T> Predicate<T> join(final Predicate<T> p1, final Predicate<T> p2)
As the compiler is trying to tell you, your method returns Predicate
, not Predicate<T>
.
Don't do that.
If you make a generic class, you should always use it with generic parameters.
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