Generics in Java
Generics in Java is similar to templates in C++. The idea is to allow type (Integer, String, … etc and user defined types) to be a parameter to methods, classes and interfaces. For example, classes like HashSet, ArrayList, HashMap, etc use generics very well. We can use them for any type.
Like C++, we use <> to specify parameter types in generic class creation. To create objects of generic class, we use following syntax.
// To create an instance of generic class BaseType <Type> obj = new BaseType <Type>() Note: In Parameter type we can not use primitives like 'int','char' or 'double'.
Output:
15 GeeksForGeeks
We can also pass multiple Type parameters in Generic classes.
Output:
GfG 15
We can also write generic functions that can be called with different types of arguments based on the type of arguments passed to generic method, the compiler handles each method.
Output :
java.lang.Integer = 11 java.lang.String = GeeksForGeeks java.lang.Double = 1.0
Programs that uses Generics has got many benefits over non-generic code.
- Code Reuse: We can write a method/class/interface once and use for any type we want.
- Type Safety : Generics make errors to appear compile time than at run time (It’s always better to know problems in your code at compile time rather than making your code fail at run time). Suppose you want to create an ArrayList that store name of students and if by mistake programmer adds an integer object instead of string, compiler allows it. But, when we retrieve this data from ArrayList, it causes problems at runtime.Output :
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String at Test.main(Test.java:19)
How generics solve this problem?
At the time of defining ArrayList, we can specify that this list can take only String objects.
.
Output:
15: error: no suitable method found for add(int) al.add(10); ^
.
.
No comments:
Post a Comment