Skip to content
Related Articles

Related Articles

Improve Article

Non-generic Vs Generic Collection in Java

  • Last Updated : 24 Dec, 2018

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.




    // 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);
            }
        }
    }

    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.




    // 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);
        }
    }

    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:




    // 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);
        }
    }

    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.




    // 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);
        }
    }
  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:

BasisNon-generic CollectionGeneric Collection
SyntaxArrayList list = new ArrayList();ArrayList list = new ArrayList();
Type-safetyCan hold any type of data. Hence not type-safe.Can hold only the defined type of data. Hence type safe.
Type castingIndividual type casting needs to be done at every retrieval.No type casting is needed.
Compile-Time CheckingChecked for type safety at runtime.Checked for type safety at Compile-time.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :