I have an interface called InterA which has a method call operate() that has its return value as Result.
public interface InterA<T>
{
Result operate(T source);
}
Assume Class MachineOperator and Class CarOperator are implementations of the above with two T object types.
public class MachineOperator implements InterA<Machine>
{
Result operate(Machine source)
{
//Do some operation here and return result.
}
}
public class CarOperator implements InterA<Car>
{
Result operate(Car source)
{
//Do some operation here and return result.
}
}
And I want to keep these implementations in a map so that when I give the class I can have the implementation. So my map would be like this.
Map<Class<?>, InterA<T>> map = new HashMap<>();
And when I go to fill the map I have to do following,
map.put(Machine.class, (InterA<T>) new MachineOperator());
map.put(Car.class, (InterA<T>) new CarOperator());
Is there any way of defining the map so there is no longer a need to cast when adding?
=============================================================
I have tried the following also which can avoid casting when adding to map.
public interface InterA
{
Result <T> operate(T source);
}
Then in each implementation I have to have additional casting for each T.
public class MachineOperator implements InterA
{
< Machine> Result operate(Machine source)
{
(Machine) source; //Need to cast for Machine In-order to read attributes.
//Do some operation here and return result.
}
}
Out of these what would be the correct approach? Is there any different solution?