Function abstraction:
public abstract class Function<X, Y> {
abstract Y apply(X x);
}
max
method implementation
public static <V extends Comparable<V>> Function<List<V>, V> max() {
return new Function<List<V>, V>() {
@Override
public V apply(List<V> list) {
return Collections.max(list);
}
};
}
And usage (how it should look like)
Date result = max().apply(datesList);
But I get this error and don't understand why it requires Object
incompatible types; inferred type argument(s) java.lang.Object do not conform to bounds of type variable(s) V
found : <V>project.Function<java.util.List<V>,V>
required: java.lang.Object
I have read big amount of similar QA but didn't get how to fix this. Thanks.
There are some fundamental differences between the two approaches to generic types. Generic Method: Generic Java method takes a parameter and returns some value after performing a task. It is exactly like a normal function, however, a generic method has type parameters that are cited by actual type.
To write a java program to find the maximum value from the given type of elements using a generic function. Create a class Myclass to implement generic class and generic methods. Get the set of the values belonging to specific data type. Create the objects of the class to hold integer,character and double values.
Generic Method: Generic Java method takes a parameter and returns some value after performing a task. It is exactly like a normal function, however, a generic method has type parameters that are cited by actual type.
The common type parameters are as follows: Like the generic class, we can create a generic method that can accept any type of arguments. Here, the scope of arguments is limited to the method where it is declared. It allows static as well as non-static methods. Let's see a simple example of java generic method to print array elements.
Java has a very limited type inference. If you write this:
Date result = max().apply(datesList);
it is not sophisticated enough to infer the type parameter of the max()
method, V
, so it takes java.lang.Object
instead. You could try this:
Function<List<Date>, Date> fn = max();
Date result = fn.apply(dates);
Or, if you want to write it in one line, you could do the following, assuming that your max()
method is defined in a class named Example
:
Date result = Example.<Date>max().apply(dates);
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