Why it is not allowed to define such a static member:
private static final <T extends Object> Map<Class<T>, BiFunction<T, T, Boolean>> SPECIFIC_HANDLERS = new HashMap<>();
Instead, he allowed the use of it unspecified:
private static final Map<Class<?>, BiFunction<?, ?, Boolean>> SPECIFIC_HANDLERS = new HashMap<>();
Is there a workaround so that I can determine that both parameters for BiFunction MUST be of the same type and that the map key must be a class type of these parameters?
Updated for clarification (because @Mena's suggestion is not suitable for me):
I want the map for the array to be equal to the method for the general equals helper. The general assistant receives formally two objects. If they are arrays, I must pass them to one of the overloaded Arrays.equals () methods. I tried to find the correct method (example 1):
private static final Map<Class<?>, BiFunction<?, ?, Boolean>> ARRAY_EQUALS_HANDLER = new HashMap<>(); static { ARRAY_EQUALS_HANDLER.put( Object[].class, (l, r) -> Arrays.equals( (Object[]) l, (Object[]) r )); ARRAY_EQUALS_HANDLER.put( boolean[].class, (l, r) -> Arrays.equals( (boolean[]) l, (boolean[]) r )); .... }
and then using it like:
boolean equal = ARRAY_EQUALS_HANDLER.get( anObj1.getClass()).apply(anObj1, anObj2);
The design (according to Mena) does not even compile:
private static <T extends Object> Map<Class<T>, BiFunction<T, T, Boolean>> getSpecificHandlers() { Map<Class<T>, BiFunction<T, T, Boolean>> result = new HashMap<>(); result.put( Object[].class, (l, r) -> Arrays.equals( (Object[]) l, (Object[]) r )); result.put( boolean[].class, (l, r) -> Arrays.equals( (boolean[]) l, (boolean[]) r )); return result; }
And if I fill in the generated map outside the method:
@SuppressWarnings( { "unchecked", "rawtypes" }) private static final Map<Class<?>, BiFunction<?, ?, Boolean>> ARRAY_EQUALS_HANDLER = (Map) getSpecificHandlers(); static { ARRAY_EQUALS_HANDLER.put( Object[].class, (l, r) -> Arrays.equals( (Object[]) l, (Object[]) r )); ... }
then the safety of the whole type disappeared because I have to make the (unchecked) type when assigning it to the last static member.
My example 1 works, but I have to use the resulting lambda when using it:
private static <T extends Object> boolean equalsArray( T anArray, T anOtherArray) { Object o = ARRAY_EQUALS_HANDLER.get( anArray.getClass()); @SuppressWarnings( "unchecked") BiFunction<T, T, Boolean> func = (BiFunction<T, T, Boolean>) o; Boolean result = func.apply( anArray, anOtherArray); return result; }