0% found this document useful (0 votes)
6 views2 pages

Generics

Java Generics, introduced in J2SE 5, enhances type safety by enforcing the storage of specific object types in collections, preventing bugs at compile time. The main advantages include type safety, elimination of type casting, and compile-time checking, which helps avoid runtime errors. This results in more stable and reliable code compared to non-generic collections.

Uploaded by

Suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Generics

Java Generics, introduced in J2SE 5, enhances type safety by enforcing the storage of specific object types in collections, preventing bugs at compile time. The main advantages include type safety, elimination of type casting, and compile-time checking, which helps avoid runtime errors. This results in more stable and reliable code compared to non-generic collections.

Uploaded by

Suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Generics in Java

The Java Generics programming is introduced in J2SE 5 to deal with


type-safe objects. It makes the code stable by detecting the bugs at
compile time.

Before generics, we can store any type of objects in the collection, i.e.,
non-generic. Now generics force the java programmer to store a specific
type of objects.

Advantage of Java Generics


There are mainly 3 advantages of generics. They are as follows:

1) Type-safety: We can hold only a single type of objects in generics. It


doesn?t allow to store other objects.

Without Generics, we can store any type of objects.

1. List list = new ArrayList();


2. list.add(10);
3. list.add("10");
4. With Generics, it is required to specify the type of object we need to store.

5. List<Integer> list = new ArrayList<Integer>();


6. list.add(10);
7. list.add("10");// compile-time error

2) Type casting is not required: There is no need to typecast the


object.

Before Generics, we need to type cast.

1. List list = new ArrayList();


2. list.add("hello");
3. String s = (String) list.get(0);//typecasting
4. After Generics, we don't need to typecast the object.
5. List<String> list = new ArrayList<String>();
6. list.add("hello");
7. String s = list.get(0);
3) Compile-Time Checking: It is checked at compile time so problem
will not occur at runtime. The good programming strategy says it is far
better to handle the problem at compile time than runtime.

1. List<String> list = new ArrayList<String>();


2. list.add("hello");
3. list.add(32);//Compile Time Error

You might also like