This method exists for the sole purpose of creating a predicate that you can use in higher order functions. For instance, here's how you could check that a list of Strings contains a specific string, if the contains() method didn't exist:
Now, this would work even if isEqual() had the following declaration:
That's because Stream.anyMatch() accepts a Predicate<? super T>.
However, some libraries aren't that well written and instead of a Predicate<? super T>, they accept a Predicate<T>.
What would happen if Stream.anyMatch() accepted a Predicate<T>, AND Predicate.isEqual() returned a Predicate<Object>? The snippet I wrote at the very top wouldn't compile, because Predicate<String> is not assignable from Predicate<Object>.
Instead, even if anyMatch() was poorly written, it would work if the declaration of Predicate.isEqual() is as it is now, because it infers that the type that it needs to return is a Predicate<String>. That's why it uses a type parameter.
(1) isEqual(Object targetRef) The parameter declaration says thay you can pass the instance of any class to this method. All the classes in Java are subclasses of the Object class.
(2) <T> Predicate<T> The T is a place holder for a specific type. Normally, if you want to create a list designed to hold only instances of Dog, you would write List<Dog>. However, in the context of isEqual() method, you have not way to know the class of the instance that will be passed to the method. That means you have no way to know the class of instances that the predicate will be testing. Even so, the class can be inferred from the argument passed to the method. Therefore, the <T> before the Predicate<T> is Java's way of saying "the T will be replaced with the class of the argument passed to the method".
Now, if you do the floowing:
Java will work out the fact the dog was created from Dog. Therefore, the isEqual() method will return type Predicate<Dog>. The T has been replaced with Dog. If you now try to use this predicate to test instances of Cat, the compiler will shoot out an error because a Cat class is not a Dog class.
Paddy spent all of his days in the O'Furniture back yard with this tiny ad: