4

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.

Community
  • 1
  • 1
leco
  • 1,989
  • 16
  • 30

2 Answers2

8

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)
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
6

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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964