Durgesh K. Singh
Durgesh K. Singh

Reputation: 39

What Benefit Generics provide over legacy Code:

i have read on docs.oracle site that The following code snippet without generics requires casting:

List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);

but if i write code with Generics then it is still prone to Error:

List<Object>= new List<Object>;
list.add("hello");
String s=(String)list.get(0);

what is then the real use of generics....:( thnx in advance..

Upvotes: 1

Views: 103

Answers (4)

Anirudha
Anirudha

Reputation: 32807

Suppose you want to store a list of names(string)

List listNames = new ArrayList();
listNames.add("Durgesh");//ok

But I could also add an integer to it

listNames.add(5000);//storing int instead of string

Now do this

String name2=listNames.get(1);//throws exception{int->string}

Without generics you could add invalid types to collection which could break your code.


With generics you could solve the problem

List<String> listNames = new ArrayList();
listNames.add("Durgesh");
listNames.add(3000);//would through error at compile time

So,generics provides typesafety


With List<Object> you intend to add any kind of Object.Due to Object parameter,it would allow you to add any kind of object(string,int).


Also List<x> cannot be assinged(=) to List<y> or vice versa if x can be converted to y or y can be converted to x..They both should be x or y thus providing type safety

So,you wont be able to assign(=) List<String> to List<Object> or vice versa..

Upvotes: 3

sanbhat
sanbhat

Reputation: 17622

Generics are used to detect runtime exceptions at compile-time itself.

Assume that you created a List to store Strings and passed it to a method.. enhanceList(List).. and after the execution, you will iterate through the list and get all strings

before genercis, it could have been possible that enhanceList(List) method will add other type of objects into the list creating possible ClassCastException

void someMethod() {
   List listOfStrings = new List();
   enhanceList(listOfStrings);

   for(Iterator i : listOfStrings.iterator(); i.hasNext();) {
        String s = (String) i.next(); //RuntimeException here
   }
}

void enhanceList(List l) {
    l.add(new Integer(1)); //error code
}

with generics, you can very well "bind" the type of objects the list contains

void someMethod() {
   List<String> listOfStrings = new List<String>();
   enhanceList(listOfStrings);

   for(String s : listOfStrings) {
       //no error here
   }
}

void enhanceList(List<String> l) {
    l.add(new Integer(1)); //compile-time error
}

However, generics should be used with caution, List<Object> doesn't help much with binding types because, it can hold any objects (since Object is super class of all the java classes). I recommend to create List of Specific type always.

Upvotes: 1

Masudul
Masudul

Reputation: 21971

Using generics makes your code Type Safe. You can prevent ClassCastException.

Upvotes: 3

Karthik T
Karthik T

Reputation: 31952

List<Object>= new List<Object>;
list.add("hello");
String s=(String)list.get(0);

Should be

List<String>= new ArrayList<String>();    // this is now a list of String, not a list of object
     ^^^^^^                 ^^^^^^
list.add("hello");
String s=list.get(0);    // no casting needed
         ^

You parameterize by the type you want. Your example are 2 ways to do the same thing, since you parameterize by the most basic class.

The advantage of generics is that you can write classes that are more specific to one class, String here. This gives you better type safety to catch bugs early during compilation. This prevents issues arising from the casting approach.

Upvotes: 4

Related Questions