How Generics Work in Java?

Published by user on

Let’s examine how generics work in Java. Also, we will look at how generics is a compile-time feature.

To demonstrate this concept, we are going to mix generic and non-generic types. But in the real world never mix these two types.

Let’s try to mix the generic and non-generic types to understand the concept better.

Mixing Generic and Non-Generic Types

This demonstration is to understand how generics is a compile-time feature.

import java.util.ArrayList;
import java.util.List;

// This program shows
// how generics work internally
public class GenericsInternalWorking {
	public static void main(String[] args) {
		// Create an instance
		// of ArrayList
		List<String> names = new ArrayList<>();
		// Add names to it
		names.add("James");
		names.add("Adam");
		names.add("Chris");
		// Print the names
		System.out.println("List elements are : " + names);
		// Pass names to the method that adds int
		// Here we are mixing generic and
		// non generic types
		// i.e. passing List<String> to just List
		addIntToNames(names, 500);
		// Print the names
		// after adding 500
		System.out.println("List elements are : " + names);
	}

	// This method accepts raw generic type
	// So we can add anything to this list
	private static void addIntToNames(List names, int i) {
		names.add(i);
	}
}

Output

List elements are : [James, Adam, Chris]
List elements are : [James, Adam, Chris, 500]

Explanation

  • Create an instance of ArrayList of String
  • Now, we can only add String to it
  • Add names James, Adam, and Chris. Till this point, the compiler makes sure that only String can be added to the list
  • Pass List<String> to the method addIntToNames() that accepts List without generics
  • Now, you can add an int to the list. So add an int i.e. 500 to the list
  • Value 500 gets added to the list as the list is of raw type
  • This demonstrated that mixing generic and non-generic types can be problematic
  • Also, we successfully added 500 to the list. This shows that the underlying list can hold any type and generics is only a compile-time feature

Conclusion

  1. Generic is only a compile-time feature
  2. Compile makes sure that the correct type must be added to the collection
  3. But if we mix the generic and non-generic types in the code then any value can be added to the collection using the non-generic list

 

Categories: Java