top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the benefit of Generics in Collections Framework?

+1 vote
394 views
What is the benefit of Generics in Collections Framework?
posted Aug 11, 2017 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn 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, 2017 by Manikandan J
...