I want to code a single method add()
in Java, that could add both integers, strings etc. Is Generics will help me.
I couldn't understand the ultimate aim of Generics. I am so confused.
Generics vs Overloading?
public Integer add(Integer i, Integer j){return i+j;}
public String add(String i, String j){return i+j;}
public <T> T add(T i, T j){return i+j;} //this gives me error.
Please get me out of it.
Thanks.
Generics could help, the problem here is that the +
operation is only defined for java primitives and String
but not for types in general. And in Java we can't overload operators (like we can do in C++ for instance).
A practical solution without generics would be:
public Integer add(Integer a, Integer b) { return a + b; } // sum of a and b
public String add(String a, String b) { return a + b; } // concatenate operation!
public MyType add(MyType a, MyType b) { return a.add(b); } // requires add operation
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