Menu
Topics Index
...
`


Collections Framework >
Siva Nookala - 20 Feb 2017
There are numerous advantages because Collections can be Generic. As you know Generics help is removing the duplicate code and provide compile time safety for the type of objects used for calling various methods.

A simple program for creating a list of friends with out using Generics will look like this.
List friends = new ArrayList();
friends.add("Shiva");
friends.add("Dhaval");
friends.add("Trupthi");
friends.add("Sudheer");

// THIS IS DANGEROUS SINCE WE ARE TYPE CASTING
String secondFriend = (String) friends.get(1); // LINE A
System.out.println("Second friend is " + secondFriend);
It is dangerous and not a good practice to upcast any Object, since it can lead to ClassCastExceptions.

Instead if we used Generic Collections, then we can do the same program with out having to upcast the object.
List<String> friends = new ArrayList<String>();
friends.add("Shiva");
friends.add("Dhaval");
friends.add("Trupthi");
friends.add("Sudheer");

// SAFE SINCE COMPILE TIME CHECKS ARE PERFORMED.
String secondFriend = friends.get(1); // LINE A
System.out.println("Second friend is " + secondFriend);

So it is suggested, we use the Generic Collections where ever possible. It is extremely rare to use any Collection like List, Set or Map without mentioning the type of the collection as Generic. Some examples of the declaration of generics are
List<Integer> fibonacciNumbers = new ArrayList<Integer>();
Map<String, Double> percentages = new HashMap<String, Double>();
Set<Character> uniqueCharacters = new HashSet<Character>();
//List of Sets
List<Set<Integer>> rollNumbersInMultipleSections = new ArrayList<Set<Integer>>();

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App