Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe for all free courses

How to create Generic Type specific Collections in Java ?

Program to demonstrate how we can create Generic Type specific Collections in Java

package com.hubberspot.example;

import java.util.ArrayList;

public class GenericTypeSafeCollections {
 
   public static void main(String[] args) {
  
   // Raw type ArrayList compiler throws warning
   // this collection is not type safe 
 ArrayList list = new ArrayList();
   // Anything can go in the ArrayList declared
   // as raw type 
 list.add(1); // Integer
 list.add("Jonty"); // String
 list.add(1.2f); // Float
 list.add(new Object()); // Object
 list.add(new String[]{ "Raw" , "Type"}); // String Array
  
   // When we retrieve elements from raw type we can get wrong 
   // element that we did not expect so everytime we get is the 
   // raw Object that we have to typecast in order to get our 
   // required type ... 
 Integer i = (Integer)list.get(1); // casting required
 String s = (String)list.get(2); // casting required
  
  
   // To make Type Safe and specific collections we use generics
   // Lets see demo below 
  
 ArrayList< String > genericList = new ArrayList< String >();
 genericList.add("Jonty");
 genericList.add("Magicman");
 genericList.add(1); // Compiler error only Strings allowed
 genericList.add(1.2f); // Compiler error only Strings allowed
  
   // When we retrieve elements from generic type we will only get 
   // right element that we expect, so everytime we get is the 
   // generic String. We dont have to typecast because compiler knows 
   // that collection will have only String in it ...
  
 String gs = genericList.get(0);
 String gss = genericList.get(1);

   }

}




 
© 2021 Learn Java by Examples Template by Hubberspot