[go: up one dir, main page]

0% found this document useful (0 votes)
23 views12 pages

Generic

Uploaded by

vikram.singh6822
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
23 views12 pages

Generic

Uploaded by

vikram.singh6822
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 12
Core java NAGOOR BABU Agend: 1) 2) 3) 4) 5) 6) Generics Introduction Generic Classes Bounded Types Generic methods and wild card character Communication with non generic code Conclusions Introduction: Case 1: Arrays are always type safe that is we can provide the guarantee for the type of elements present inside array. For example if our programming requirement is to hold String type of objects it is recommended to use String array. in the case of string array we can add only string type of objects by mistake if we are trying to add any other type we will get compile time error. Example: String[] s=new String{600]; s(0]="durga" s[1]="pavan"; :\SCIP>javac Test.java s[2]=new Integer(10);(invalid) GE > Test java:8: incompatible types found : java.lang.integer required: java.tang.String That is we can always provide guarantee for the type of elements present inside array and hence arrays are safe to use with respect to type that is arrays are type safe. But collections are not type safe that is we can’t provide any guarantee for the type of ‘elements present inside collection. For example if our programming requirement is to hold only string type of objects it is never recommended to go for ArrayList. By mistake if we are trying to add any other type we won't get any compile time error but the program may fail at runtime. 397 DURGA SOFT Core java NAGOOR BABU Example: ‘ArrayList lenow ArrayList(); - Ladd("vijaya"); Ladd{"bhaskara"); . Ladd{new integer(10)}; eee String namei=(string).get(0}; String name2=(String)}.get{2}; String name3=(String)l.get(2}:{invalid). ‘* Hence we can’t provide guarantee for the type of elements present inside collections that is collections are not safe to use with respect to type. Case 2: In the case of array at the time of retrieval it is not required to perform any type casting. Example: String] ssnew String[600}; type casting is not required. ‘* Buti the case of collection at the time of retrieval compulsory we should perform type casting otherwise we will get compile time error. Example: ArrayList Isnew ArrayList(); Ladd("vijaya"); Ladd{"bhaskara"); String name1=,l.get(0); Es rest.java:9: Incompatible types found: java.lang.Object required: java.lang.String, \t the time of -asting is Mandator String name1=(string)|.get(0); ‘* Thats n collections type casting is bigger headache. 398, DURGA SOFT Core java NAGOOR BABU © To overcome the above problems of collections(type-safety, type casting)sun people introduced generics concept in 1.5v hence the main objectives of generics are: 1) To provide type safety to the collections. 2) To resolve type casting problems. * To hold only string type of objects we can create a generic version of ArrayList as follows. example: Arraylist I=new ArrayListeString>(); toa i [Fest java:S: cannot find symbol Hl symbol : method ada{int) location: class java.util ArrayListsjava Ladd(10); ‘For this ArrayList we can add only string type of objects by mistake if we are trying to add any other type we will get compile time error that is through generics we are getting type safety. © At the time of retrieval it is not real elements directly to string type variables. Example: id to perform any type casting we can assign ArrayList Isnew ArrayList(); Ladd("A"); String namei=/|.get(0); L Siype casting is not required © That is through generic syntax we can resolve type casting problems. Conclusion: * Polymorphism concept is applicable only for the base type but not for parameter typelusage of parent reference to hold child object is called polymorphism} Example: parameter type ArrayList I1=new ArrayList(); base Type List I2=new Arraylist(}; Collection I3=new ArrayList(}; incompatible types Arraylist M=new Arraylist();-GE >| 399) DURGA SOFT Core java NAGOOR BABU Concluson2; © For the parameter type we can use any class or interface but not pri Example: ArrayListcint> Isnew ArrayListcint>(); itive value(type). Arraylistcint> tsnew Arraylist(); Generic classes: © Untild.4v ArrayList class is declared as follows. Example; class ArrayList { add(Object o); Object get{int index); ‘* addi) method can take object as the argument and hence we can add any type of object to the ArrayList. Due to this we are not getting type safety. ‘+ The return type of get{) method is object hence at the time of retrieval compulsory we should perform type casting. © Butin 1.5va generic version of ArrayList class is declared as follows. Beample;: ‘Type parameter dass Aran : ada T gat{int index}; , © Based on our requirement T will be replaced with our provided type. For Example * Tohold only string type of objects we can create ArrayList object as follows. Example: ArrayList lsnew ArrayList(); ‘* For this requirement compiler considered ArrayList class is Example: class Arraylist { add(String s); String get(int index); DURGA SOFT Core java NAGOOR BABU ‘© add() method can take only string type as argument hence we can add only string type of objects to the List. By mistake if we are trying to add any other type we will get compile time error. public static void main(String{] args) { ArrayList Ienew Arrayist(); add("A"); . i FTest.java:8: cannot find symbol ) add(10}; GE >| abot : method add{int) location: class java.u ladd(10); * Hence through generics we are getting type safety. © At the time of retrieval it is not required to perform any type casting we can assign its values directly to string variables. .ArrayList| import java.util. class Test { public static void main(String{] args) { Ladd("10"}; String name1=l.get(0); + fe casting is not required * Based on our requirement we can create our own generic classes also. } Example: class Account o Account gl=new Account); Account g2=new Account(); Example: class UDGenerics { T obj; 401 DURGA SOFT Core java NAGOOR BABU UDGenerics(T obj) { this.obj=obj; d public void show() { System.out.printin("The type of object is "+obj.getClass().getName()); } public T getObject() { return obj; } } class GenericsDemo { public static void main(String{] args) { UDGenerics gl=new UDGenerics(10); gi.show(); System.out.printin(g1.getObject()); UDGenerics g2=new UDGenerics("bhaskar"); g2.show\); System.out.printin(g2.getObject()); UDGenerics g3=new UDGenerics(10. g3.show(); System. out printin(g3.getObject()); } } Output: The type of object is: java.lang.integer 10 The type of object is: java.lang. String Bhaskar The type of object is: java.lang. Double 105 Bounded types: ‘* We can bound the type parameter for a particular range by using extends keyword such types are called bounded types. 402 DURGA SOFT Core java NAGOOR BABU Example 1; class Test tt Test t1=new Test < Integer>();, Test t2=new Test < String>(); * Here as the type parameter we can pass any type and there are no restrictions hence it is unbounded type. Example 2: class Test iv + Ifxis a class then as the type parameter we can pass either x or its child classes. ‘+ If xis an interface then as the type parameter we can pass either x or its implementation classes. Example 1: class TestcT extends Number> 0 class Testi { Public static void main(Stringf] args) { Test ti=new Test(); + ‘ rast suis ase tack saint type parameter java.lang.String is not within its bound] ‘ oe > [ Testestring> t2-now Testcstring>(}; , Example 2: class Test 0 class Test 4 public static void main(String] args) { ‘TesteThread> t1=now Test(); ‘Test t2=new Test| class TestcT super String> a a (invalid) (invatia) «But implements keyword purpose we can replace with extends keyword. ‘403 DURGA SOFT 403 Core java NAGOOR BABU ‘* As the type parameter we can use any valid java identifier but it convention to use T always. Example: class Test| class Test o o * We can pass any no of type parameters need not be one. Example: key type class bashatanekv> o L__-value type HashMap h=new HashMapcInteger,String>(); * We can define bounded types even in combination also. Example 1: class Test {Hvalid) ‘* As the type parameter we can pass any type which extends Number class and implements Runnable interface. Example 2: class Test ‘{i(valid) Example 3: class Test (invalid) ‘© We can’t extend more than one class at a time. Example 4: class Test ‘valid Example 5: class Test {Minvalid) © We have to take 1* class followed by interface. thi a (2: methodOne(ArrayList I}: This method is applicable for ArrayList of only String type. Example: Ladd("A"); Ladd(null); Ladd(10);//(invalid) 404 DURGA SOFT Core java NAGOOR BABU © Within the method we can add only String type of objects and null to the List. methodOne(Arraylist I); We can use this method for ArrayList of any type but within the method we can't add anything to the List except null. Example: Ladd(null);//(valid) Ladd("A");//invalid) L.add(10);//(invalid) ‘© This method is useful whenever we are performing only read operation. m < : is method is applicable for ArrayList of either x type or its child © If xis a class then classes. ‘* If xis an interface then this method is applicable for ArrayList of either x type or its implementation classes. ‘© _Inthis case also within the method we can’t add anything to the List except null. methodOne(Arraylist I): ‘* If xis a class then this method is applicable for ArrayList of either x type or its super classes. * If xis an interface then this method is applicable for ArrayList of either x type or super classes of implementation class of x. ‘© But within the method we can add x type objects and null to the List. Which of the following declarations are allowed? 1) ArrayList I1=new ArrayList();//(valid) 2) ArrayList I2=new ArrayList();//(valid) 3) ArrayList I3=new ArrayList();//{(valid) 4) ArrayList I4=new Arraylist();//(valid) 5) ArrayList IS=new ArrayList();(invalid) Output: Compile time error. Test,java:10: incompatible types Found : java.util. ArrayList Required: java.util. ArrayList Arraylist IS=new Arraylist(); 6) Arraylist<2> I6=new ArrayList(); Output: Compile time error Test java:11: unexpected type found : ? extends java.lang.Number required: class or interface without bounds 405, DURGA SOFT ans Core java NAGOOR BABU ArrayList l6=new ArrayList();, 7) ArrayList I7=new Arraylist(); : unexpected type Required: class or interface without bounds ArrayList I7=new Arraylist(); © We can declare the type parameter either at class level or method level. Declaring type parameter at class level; class Test { ‘We can use anywhere this T'. Declaring type parameter at method level: © We have to declare just before return type. Example: public void methodOne1(T t){}//valid public void methodOne2(T t){}//valid public void methodOne3{T t}{}//valid public void methodOne4{T t){}//valid public void methodOne(T t}{}//invalid interface expected here public void methodOne(T t){}//valid public void methodOne(T t){}//invalid time error. : interface expected here public void methodOne(T t){}//valid Communication with non generic code: © To provide compatibility with old version sun people compramized the concept of generics in very few area’s the following is one such area. Example: import java.util.*; class Test { public static void main(String{] args) 406 DURGA SOFT Core java NAGOOR BABU { Arraylist Ienew ArrayList(); ladd("a"); //\.add(10);//C.E:cannot find symbol,method add{(int) methodOne(!); |1.add(10.5);//C.E:cannot find symbol,method add(double) System.out.printin(l);//{A, 10, 10.5, true] } public static void methodOne(ArrayList I) { Ladd(10); Ladd(10.5); ladd(true); } Note: * Generics concept is applicable only at compile time, at runtime there is no such type of concept. Hence the following declarations are equal. ArrayList l=snew ArrayList(); ArrayList I=new ArrayList(); | All are equal. ArrayList [snew ArrayList(); Example 1: import java.util.*; class Test { Public static void main(Stringf] args) { ArrayList Isnew ArrayList(); Ladd(10); Ladd(10.5); ladd(true); System.out.printin(!);// (20, 10.5, true] } } Example 2: import java.util.*; class Test { 407 DURGA SOFT 407 Core java NAGOOR BABU public void methodOne(ArrayList I{} public void methodOne(Arraylist I}{} } Output Compile time error. Test.java:4: name clash: methodOne(java.util ArrayList) and me thodOne(java.utl.Arraylist) have the same erasure public void methodOne(ArrayList I}{} © The following 2 declarations are equal. ArrayList I1=new ArrayList(); Arraylist I2=new ArrayList(); * For these ArrayList objects we can add only String type of objects. Example: M1.add("A");//valid {1.add(10); //invalid DURGA SOFT

You might also like