Generics
Generics in java is introduced as a feature in JDK 5. In general, generics force type safety in java. Generics make your code easy during compile time for type checking. Below two are the two main advantages i see in using generics.a) Type Safety:
It’s just a guarantee by compiler that if correct Types are used in correct places then there should not be any
ClassCastException
in runtime. A usecase can be list of Integer
i.e. List<Integer>
. If you declare a list in java like List<Integer>
, then java guarantees that it will detect and report you any attempt to insert any non-integer type into above listb) Type Erasure: It essentially means that all the extra information added using generics into sourcecode will be removed from bytecode generated from it. Inside bytecode, it will be old java syntax which you will get if you don’t use generics at all. This necessarily helps in generating and executing code written prior java 5 when generics were not added in language.
Let’s understand with an example.
List<Integer> list = new ArrayList<Integer>(); list.add( 1000 ); // works fine list.add( "santhosh" ); // compile time error |
When you write above code and compile it, you will get error as : “The method add(Integer) in the type
List<Integer>
is not applicable for the arguments (String)“. Compiler will warne you. This exactly is generics sole purpose i.e. Type Safety.Second part is getting byte code after removing second line from above example. If you compare the bytecode of above example with/without generics, then there will not be any difference. Clearly compiler removed all generics information. So, above code is very much similar to below code without generics.
List list =
new
ArrayList();
list.add(
1000
);
Generic Types:
Generic Type Class or Interface :For example, we can right a simple java class as below with out generics representation.
class
Simple
Class {
private
Object
t;
public
void
set(Object t) {
this
.t = t; }
public
Object
get() {
return
t; }
}
Here we want that once initialized the class with a certain type, class should be used with that particular type only. e.g. If we want one instance of class to hold value t of type ‘
String
‘, then programmer should set and get the only String
type. Since we have declared property type to Object
,
there is no way to enforce this restriction. A programmer can set any
object; and can expect any return value type from get method since all
java types are subtypes of Object
class.class
SimpleGeneric
Class<T> {
private
T
t;
public
void
set(T t) {
this
.t = t; }
public
T
get() {
return
t; }
}
Generic Type Method or Constructor
No comments :
Post a Comment