Generics

17 Oct 2024 . java .

Generic Class

class Test<T> {
	T obj;
	Test(T obj) { this.obj = obj; } 
	public T getObject() { return this.obj; }
}

class Main {
	public static void main(String[] args)
	{
		// instance of Integer type
		Test<Integer> iObj = new Test<Integer>(15);
		System.out.println(iObj.getObject());

		// instance of String type
		Test<String> sObj
			= new Test<String>("GeeksForGeeks");
		System.out.println(sObj.getObject());
	}
}

Generic Method

class Test {
	static <T> void genericDisplay(T element)
	{
		System.out.println(element.getClass().getName()
						+ " = " + element);
	}

	public static void main(String[] args)
	{
		// Calling generic method with Integer argument
		genericDisplay(11);

		// Calling generic method with String argument
		genericDisplay("GeeksForGeeks");

		// Calling generic method with double argument
		genericDisplay(1.0);
	}
}

Work Only with Packaging Types

Test<int> obj = new Test<int>(20);

Results in a compile-time error that can be resolved using type wrappers to encapsulate a primitive type.

Advantages

  • Code Reuse: We can write a method/class/interface once and use it for any type we want.
  • Type Safety: Generics make errors to appear compile time than at run time.
    • Example:

        class Test
        {
        	public static void main(String[] args)
        	{
        		// Creatinga an ArrayList without any type specified
        		ArrayList al = new ArrayList();
              
        		al.add("Sachin");
        		al.add("Rahul");
        		al.add(10); // Compiler allows this
              
        		String s1 = (String)al.get(0);
        		String s2 = (String)al.get(1);
              
        		// Causes Runtime Exception
        		String s3 = (String)al.get(2);
        	}
        }
      
        Exception in thread "main" java.lang.ClassCastException:
           java.lang.Integer cannot be cast to java.lang.String
            at Test.main(Test.java:19)
      

        class Test
        {
        	public static void main(String[] args)
        	{
        		// Creating a an ArrayList with String specified
        		ArrayList <String> al = new ArrayList<String> ();
              
        		al.add("Sachin");
        		al.add("Rahul");
              
        		// Now Compiler doesn't allow this
        		al.add(10);
              
        		String s1 = (String)al.get(0);
        		String s2 = (String)al.get(1);
        		String s3 = (String)al.get(2);
        	}
        }
      
        15: error: no suitable method found for add(int)
                al.add(10);
                  ^
      
  • Individual Type Casting is not needed: If we do not use generics, every time we retrieve data from ArrayList, we have to typecast it. Typecasting at every retrieval operation is a big headache. If we already know that our list only holds String data, we need not typecast it every time.