Non-generic Vs Generic Collection in Java

Differences between Non-generic and Generic Collection

Programs that uses Generics has got many benefits over non-generic code.

  1. Code Reuse: By using Generics, one needs to write a method/class/interface only once and use for any type. Whereas in the non-generics, the code needs to be written again and again whenever needed.
  2. Type Safety: Generics make errors to appear compile time than at run time (It’s always better to know problems in your code at compile time rather than making your code fail at run time).

    For Example: To create an ArrayList that store name of students and if by mistake programmer adds an integer object instead of string, compiler allows it. But, when this data is retrieved from ArrayList, it causes problems at runtime for Non-generic ArrayList.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // A Simple Java program to demonstrate that NOT using
    // generics can cause run time exceptions
      
    import java.util.*;
      
    class Test {
        public static void main(String[] args)
        {
            // Creating 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);
      
            try {
                // Causes Runtime Exception
                String s3 = (String)al.get(2);
            }
            catch (Exception e) {
                System.out.println("Exception: " + e);
            }
        }
    }

    chevron_right

    
    

    Output:

    Exception:
     java.lang.ClassCastException:
     java.lang.Integer cannot be cast to java.lang.String
    

    How generics solve this problem: If this list was made Generic, then it would take only String objects and threw Compile Time Error in any other case.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Using generics converts run time exceptions into
    // compile time errors
      
    import java.util.*;
      
    class Test {
        public static void main(String[] args)
        {
            // Creating 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 = al.get(0);
            String s2 = al.get(1);
            String s3 = al.get(2);
        }
    }

    chevron_right

    
    

    Output:

    15: error: no suitable method found for add(int)
            al.add(10); 
              ^
    
  3. Individual Type Casting is not needed: If Generics is not needed, then, in the above example every-time the data is to be retrieved from ArrayList, it needs to be typecasted. Typecasting at every retrieval operation is a big headache. This can be avoided if by somehow it is already known that the list only holds string data.

    For Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // A Simple Java program to demonstrate that
    // type casting is needed everytime in Non-Generic
      
    import java.util.*;
      
    class Test {
        public static void main(String[] args)
        {
            // Creating an ArrayList without any type specified
            ArrayList al = new ArrayList();
      
            al.add("Sachin");
            al.add("Rahul");
      
            // For every retrieval,
            // it needs to be casted to String for use
            String s1 = (String)al.get(0);
            String s2 = (String)al.get(1);
        }
    }

    chevron_right

    
    

    How generics solve this problem: If this list was made Generic, then it would take only String objects and would return only String object while retrieval. And hence individual type casting wont be required.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // A Simple Java program to demonstrate that
    // type casting is not needed in Generic
      
    import java.util.*;
      
    class Test {
        public static void main(String[] args)
        {
            // Creating an ArrayList with String specified
            ArrayList<String> al = new ArrayList<String>();
      
            al.add("Sachin");
            al.add("Rahul");
      
            // Retrieval can be easily
            // without the trouble of casting
            String s1 = al.get(0);
            String s2 = al.get(1);
        }
    }

    chevron_right

    
    

  4. Implementing generic algorithms: By using generics, one can implement algorithms that work on different types of objects and at the same they are type safe too.

There are the some points, which will describe difference between Generics and Non Generic:

Basis Non-generic Collection Generic Collection
Syntax ArrayList list = new ArrayList(); ArrayList list = new ArrayList();
Type-safety Can hold any type of data. Hence not type-safe. Can hold only the defined type of data. Hence type safe.
Type casting Individual type casting needs to be done at every retrieval. No type casting is needed.
Compile-Time Checking Checked for type safety at runtime. Checked for type safety at Compile-time.


My Personal Notes arrow_drop_up

Strategy Path planning and Destination matters in success No need to worry about in between temporary failures

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.