top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration
Print Preview

What is the benefit of Generics in Collections Framework?

+1 vote
15 views
posted Aug 11 by anonymous

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

1 Answer

0 votes

Generics in java enable types to be parameterized when defining classes, interfaces and methods. Its like familiar formal parameters used in when declare methods; type parameters provide way for us to re-use same code with different inputs parameters. Difference is that inputs to the formal parameters are values, while inputs to type parameters are types.

In java generics have many benefits over non-generic code:

Stronger type check at code compiles time.
Java compiler applies strong type checking to the generic code and issue errors if code violates type safety or not. Fixing compile time errors are easier than fixing runtime errors, which could be difficult to find.

Elimination of casting.

Below code snippet without generics requires casting:

package com.javahonk.genericstest;

import java.util.ArrayList;
import java.util.List;

public class GenericsTest {

    public static void main(String[] args) {

        List list = new ArrayList();
        list.add("Java Honk");
        // casting done for String
        String s = (String) list.get(0);
    }
}

When re-written using generics, code does not requires casting:

package com.javahonk.genericstest;

import java.util.ArrayList;
import java.util.List;

public class GenericsTest {

    public static void main(String[] args) {

        List<String> list = new ArrayList<String>();
        list.add("Java Honk");
        String s = list.get(0);
        System.out.println(s);
    }
}

It enables us to implement generic algorithms.

By using generics, we could implements generic algorithms that could work on different types of collections, could be customized, and are also type safe and easier to read.

answer Sep 14 by Manikandan J

Useful Links with Similar Problem
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...