Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are Generics in Java? [closed]

I don't really understand the point of generics. What do they do, how do you use them?

From what I can tell, all they do is check return types at compile times instead of run times to avoid running the program before an error is thrown. Is this all they do?

for example:

public <Integer> int test() {     return 'c'; //will throw error at compile instead of runtime } 

I was reading something about how generics are arbitrary, and you should only use capital letters? This is kind of confusing.

like image 728
switz Avatar asked Oct 19 '11 01:10

switz


People also ask

What are generics in Java?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.

What is generics in Java stack overflow?

Generics allow you to create a single method that is customized for the type that invokes it. T is substituted for whatever type you use.

Why are generics used in Java?

In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs.


2 Answers

Generics allow you to customize a "generic" method or class to whatever type you're working with. For example, suppose you have a method that adds two numbers together. In order to work with the types themselves, you might have to create multiple versions of this method. For instance:

public int Add(int a, int b)  public double Add(double a, double b)  public float Add(float a, float b) 

Generics allow you to create a single method that is customized for the type that invokes it.

public <T> T Add(T a, T b) 

T is substituted for whatever type you use.

like image 50
Erik Funkenbusch Avatar answered Oct 01 '22 11:10

Erik Funkenbusch


Refer to the Fundamentals in Angelika Langer's FAQ – it's the best explanation of all things related to Java's generics you're likely to find. That said, the original primary goal of generics was to enable "typed" collections.

like image 30
millimoose Avatar answered Oct 01 '22 10:10

millimoose