Loading

Generics in collections

  • Generics are mainly used in collections.
  • Generics are mainly used to store specific types of objects.
  • Generics are always defined inside the angular braces(<>).

Advantages:

  • It can hold only a single type of object, it doesn't allow it to store other objects.
  • There is no need to typecast the objects.
  • Compile time checking: It is checked at compile time so the problem will not occur at runtime.

Example:

package quipoin;

import java.util.ArrayList;

public class DemoGeneric {
	public static void main(String[] args) {

		ArrayList<String> list = new ArrayList<>();
		list.add("Java");
		list.add("Python");
		list.add("Web_Technology");
		// list.add(20); compilation error because of int type.

		System.out.println("Storing string type objects using generics!!");
		for (String elements : list) {
			System.out.println(elements);
		}
	}
}

Output:

Storing string-type objects using generics!!
Java
Python
Web_Technology
  • In the above example, we are storing specific types of objects i.e. String type, if we are trying to store other type objects compiler throws an error.