Java gen
November 19, 2017
Reading
Add Comment
Generics is a java feature introduced as part of Java 1.5. It ensures
- Type safety(provides type checking during java compile time)
- Code reusability
- Removes the possibility of classCastException during runtime.
Any generic java type(Class, interface etc) and methods are basically datatypes and functions which are strictly parameterized over a data type respectively. Since Java 5 whole collection classes are rewritten using generics to ensure type safety.
Pre Java 5 code
List myList = new ArrayList(); // cant declare a type
myList.add(new Dog()); // and it will hold Dogs too
mylist.add(new Integer(42)); // and Integers….
myList.add(“Fred”); // OK it will hold String
Here getting a String back from String-intended list requires a cast.
String s = (String) myList.get(0);
With Generics
<code>
List<String> myList = new ArrayList<String>();
myList.add(“Fred”); //OK, it will hold Strings
myList.add(new Dog()); // compiler error!!
</code>
But String s=myList.get(0);
Now myList ensures always a string to be returned.
Simillarly,
<code>
void takeListOfStrings(List<String> strings){
strings. add (“ foo”); // no problem adding a String
}
void takeListOfString( List<String> strings) {
strings.add(new Integer(42)); // NO!! Strings is type safe
}
</code>
Return types can be declared type safe
<code>
public Set<Dog> getDogList(){
Set<Dog> dogs = new HashSet<Dog>();
return dogs;
}
Dog d = getDogList().get(0);
</code>
But Pre Java 5
<code>
Public Set getDogList(){
Set dogs = new HashSet();
return dogs;
}
Dog d =(Dog) getDogList().get(0);
</code>
0 comments:
Post a Comment