Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Generics in Java? How it is different from overloading?

Tags:

java

generics

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.

like image 295
Manoj Avatar asked Jan 24 '11 13:01

Manoj


1 Answers

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
like image 89
Andreas Dolk Avatar answered Sep 18 '22 11:09

Andreas Dolk