Non-generic Vs Generic Collection in Java


Generic Collection

  • Errors appear at compile time than at run time.
  • Code reusability: Generics help in reusing the code already written, thereby making it usable for other types (for a method, or class, or an interface).
  • If a data structure is generic, say a list, it would only take specific type of objects and return the same specific type of object as output. This eliminates the need to typecast individually.
  • Algorithms can be implemented with ease, since they can be used to work with different types of objects, and maintaining type safety as well as code reusability.

Example

Following is an example −

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String[] args) {
      ArrayList<String> my_list = new ArrayList<String>();
      my_list.add("Joe");
      my_list.add("Rob");
      my_list.add("John");
      my_list.add("Billy");
      String s1 = my_list.get(0);
      String s2 = my_list.get(1);
      String s3 = my_list.get(3);
      System.out.println(s1);
      System.out.println(s2);
      System.out.println(s3);
   }
}

Output

Joe
Rob
Billy

A class named Demo contains the main function. Here, an arraylist of strings is defined. Elements are added to this list with the help of the ‘add’ function. The ‘get’ function is used to store the element at a specific index. The println function is used to print the specific element on the console.

Non - Generic Collection

  • When the data structure is non-generic, it causes issues when the data is tried to be retrieved from the collection/data structure.
  • Every time an element from the collection is retrieved, it needs to be explicitly type-casted to its required type, which is a problem when there are too many elements.

The above code, when implemented using non-generic collection yields the following output.

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String[] args) {
      ArrayList my_list = new ArrayList();
      my_list.add("Joe");
      my_list.add("Rob");
      my_list.add("Nate");
      my_list.add("Bill");
      String s1 = (String)my_list.get(0);
      String s2 = (String)my_list.get(1);
      String s3 = (String)my_list.get(3);
      System.out.println(s1);
      System.out.println(s2);
      System.out.println(s3);
   }
}

Output

:
Joe
Rob
Bill

A class named Demo contains the main function. Here, an arraylist of strings is defined. Elements are added to this list with the help of the ‘add’ function. The ‘get’ function is used to store the element at a specific index. Here, every element of the list is explicitly typecasted to String type before being stored in another string variable. The println function is used to print the specific element on the console.

Updated on: 14-Sep-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements