Generics:
Type Safety Objects: Allow one type of object, does not allow other object
No Casting required.
For example in Collection
List<String> list = new ArrayList<String>
Allow only string objects to List.
Map<String,Integer> map = new TreeMap<String,Integer>
Allow String and Integer to Map.
When we try to add number it will throw compile time.
General Generic Example
class Generic<T>{
T object;
void add(T object)
{
this.object=object;
}
T get()
{
return object;
}
public static void main(String[] args) {
Generic<Integer> ingen = new Generic<Integer>();
Generic<String> strgen = new Generic<String>();
ingen.add(new Integer(11));
strgen.add(new String("Generic"));
System.out.printf("Integer =%d", ingen.get());
System.out.printf("String =%s", strgen.get());
}
}
Print Integer =11 String =Generic.
Type Safety Objects: Allow one type of object, does not allow other object
No Casting required.
For example in Collection
List<String> list = new ArrayList<String>
Allow only string objects to List.
Map<String,Integer> map = new TreeMap<String,Integer>
Allow String and Integer to Map.
When we try to add number it will throw compile time.
General Generic Example
class Generic<T>{
T object;
void add(T object)
{
this.object=object;
}
T get()
{
return object;
}
public static void main(String[] args) {
Generic<Integer> ingen = new Generic<Integer>();
Generic<String> strgen = new Generic<String>();
ingen.add(new Integer(11));
strgen.add(new String("Generic"));
System.out.printf("Integer =%d", ingen.get());
System.out.printf("String =%s", strgen.get());
}
}
Print Integer =11 String =Generic.
No comments:
Post a Comment
Thanks for your valuable comments