0% found this document useful (0 votes)
16 views16 pages

Generics

The document provides an overview of Generics in Java, emphasizing its importance for type safety and resolving type casting issues. It explains the differences between arrays and collections, introduces generic classes and methods, and discusses bounded types. The content is structured into various sections, covering topics such as type safety, type casting, and the use of wildcards in generics.

Uploaded by

raj9301560
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)
16 views16 pages

Generics

The document provides an overview of Generics in Java, emphasizing its importance for type safety and resolving type casting issues. It explains the differences between arrays and collections, introduces generic classes and methods, and discusses bounded types. The content is structured into various sections, covering topics such as type safety, type casting, and the use of wildcards in generics.

Uploaded by

raj9301560
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/ 16
Core Java with SCJP/ OCIP Notes By Durga Sir Generics With SCIP / OCIJP Study Material Chapter 15: Generics DURGA mech (Sun certified & Realtime Expert Ex. IBM Employee Trained Lakhs of Students for last 14 years across INDIA India’s No.1 Software Training Institute DURGASOFT WWwW.durgasoft.com Ph: 9246212143 8096969696 7 | DURGASOFT, #202,2"%loor HUDA Maitrvanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Generics GENERICS Agenda: 1. Introduction 2. Type-Safety 3. Type-Casting 4. Generic Classes 5. Bounded Types 6. Generic methods and wild card character(?) 7. Communication with non generic code 8. Conclusions (ier Deff : The main objective of Generics is to provide Type-Safety and to resolve Type-Casting problems. Case 1: Type-Safety + Arrays are always type safe that is we can give 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]; E:\SCJP>javac Test.java | DURGASOFT, #702,2"*Fioor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP OCJP Notes By Dur + 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 its 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. Example: ArrayList snew Arrayist(); Laddl"vijaya"); Ladd("bhaskara’; Laddfnew Integer(10)} String name2=(String)I.get(1); String name3=(string.get(2}{invali) RE _s} Exception in thread "main" javalang.ClassCastException: ava lang Integer cannot be cast to java.lang.String 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: Type-Casting In the case of array at the time of retrieval it is not required to perform any type casting. ‘DURGASOFT, # 202,2""Floor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Generics Example: String[] s=new String[600]; s[0]="vijaya"; s[1]="bhaskara"; String name1=)s[0]; sat the time of retrieval type casting is not required. But in the case of collection at the time of retrieval compulsory we should perform type casting otherwise we will get compile time error. Example: ArrayList l=new ArrayList(); Ladd| ya"); l.add("bhaskara"); [Test.jav: incompatible types String name1=|l.get(0);Esffound : java.lang.Object required: java.lang.String String name1=l.get(0); String name1=(String)I.get(0); + Thats in collections type casting is bigger headache, 7) | DURGASOFT, #202,2"*Fioor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP OCJP Notes By Durga Sir + To overcome the above problems of collections(type-safety, type casting)sun people introduced generics concept in 1.6v hence the main objectives of generics are: 41. To provide type safety to the collections. 2. To resolve type casting problems. + Tohold only string type of objects we can create a generic version of ArrayList as follows. Examp! ArrayListString> I-new ArrayListeString>(}; Ladd("vijaya + - lava"h; ce. [Festjavais: cannot find symbol add(10);{invalid)—="> |. vmbol : method add(int) location: class java.util.ArrayList Ladd(10); eee ‘+ 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. + Atthe time of retrieval itis not required to perform any type casting we can assign elements directly to string type variables. Example: ArrayList l=new ArrayList(); Ladd{"A"); String name1=. get(0); Type casting is not required = | DURGASOFT, #202,2" Floor HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, + 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 type[usaye of parent reference to hold child object is called polymorphism]. Example: parameter type ArraylistStrng> snew AraylistString>(}; base Type ListStrng> Lsnew ArraylistString>); CollecionString> Benew Araylist String}; ArrayistcObject Menew ArraylistStrng>(}-SE-s| Anaistbecd snow Araylststringo( Concluson2: Collections concept applicable only for objects , Hence for the parameter type we can use any class or interface name but not pri value(type).Otherwise we will get compile time error. Examp! ArrayList Isnew ArrayList(); - |Test.java:6: unexpected type found : int required: reference ArrayList Isnew ArrayList(); ‘DURGASOFT, # 202,2""Floor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Generics EES Until 1.4v a non-generic version of ArrayList class is declared as follows. Example: class ArrayList { add (Object 0) ; Object get (int index) ; ‘+ add() 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. But in 1.5v a generic version of ArrayList class is declared as follows. Examp! [Type parameter class ArrayListsT: { add(T t); T get(in dex); ‘+ Based on our requirement T will be replaced with our provided type. + For Example to hold only string type of objects we can create ArrayList object as follows. Example: ArrayListeString> Irnew ArrayList(); + For this requirement compiler considered ArrayList class Is DURGASOFT, # 202,2""Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP OCJP Notes By Dur Example: class ArrayList { add (string s); String get (int index); ) 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. Example: import java.util.*; class Test { public static void main(String[] args) { ArrayList I=new ArrayList(); Ladd("A"); Test,java:8: cannot find symbol lada(t0}; >| symbol : method add{int) location: class java.util. ArrayList| Ladd(10); ‘+ Hence through generics we are getting type safety. + Atthe time of retrieval it is not required to perform any type casting we can assign its values directly to string variables. ‘DURGASOFT, # 202,2""Floor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Generics Example: import java. class Test { public static void main(String[] args) { ArrayList I=new ArrayList(); Ladd("A"); Ladd("10"); String name: et(0); } Type casting is not required In Generics we are associating a type-parameter to the class, such type of parameterised classes are nothing but Generic classes. Generic class : class with type-parameter Based on our requirement we can create our own generic classes also. Example: class Account 0 Account gi=new Account() ; Account g2=new Account(); Example: class Gen { T obj; Gen (T obj) { this. obj=obj; ) public void show() { System.out.printin("The type of object is :"40bj.getClass().getName()) ; ) public T getobject () { } return obj; ‘DURGASOFT, # 202,2""Floor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Generics , class GenericsDemo ( public static void main(String[] args) ( Gencinteger> gi=new Gen(10) ; gl.show() ; System.out.printIn (gi .getobject ()) ; Gen g2=new Gen ("Akshay") ; g2.show() ; Systen.out.printin (g2.getobject ()) ; Gen g3-new Gen (10.5) ; g3.show() ; System.out.printin(g3.getobject ()) ; , , Output: The type of object is: 10 java. lang. Integer The type of object is: java.lang. string Akshay The type of object is: java.lang. Double 10.5 Eres We can bound the type parameter for a particular range by using extends keyword such types are called bounded types. Example class Test 0 Test ti=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 class Test 0 ‘+ Ifxisa class then as the type parameter we can pass elther x or its child classes. + Ifx isan interface then as the type parameter we can pass either x or its implementation classes. 70 | DURGASOFT, #202,2" Floor RUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Generics Example 1: class Test iV class Test { public static void main(String!] args) { Test t1=new Testeinteger>(|; Gailec SCE tad Testing Dene Test tings} —{¥92 Parameter avalng String isnot within boun ) ? TesteString> t2=new Test}; Example 2: class Test tt class Test { publi stati void mainString] args) { Tete tse ete TestSting>t2=new Teststringy} CE } } + We can't define bounded types by using implements and super keyword. 71 | DURGASOFT, #202,2"Floor HUDA Maitrvanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP OCJP Notes By Dur Example: class Test| class Test t } (invalid) (invalid) + But implements keyword purpose we can replace with extends keyword. + Asthe type parameter we can use any valid java identifier but it convention to use Talways. Example: class Test| class Test {} {} ‘We can pass any no of type parameters need not be one. Examp! key type class HashMap {} L____value type HashMap h=new HashMap(); We can define bounded types even in combination also. Example class Test {}(valid) As the type parameter we can pass any type which extends Number class and implements Runnable interface. 72 | DURGASOFT, #202,2" Floor RUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Generics Example class Test {}(valid) Example 3: class Test {}(invalid) We can't extend more than one class at a time. Example 4: class Test {}(valid) Example class Test {}(invalid) We have to take 1st class followed by interface. (Generic methods and wild-card characte! methodOne(ArrayList I): This method Is applicable for ArrayList of only String type. Example: Lada ("A") ; 2.add (nu) ; 1. add (10) ;// (invalid) ‘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: 1. add (nul) ;// (valida) Ladd ("A") ;// (invalid) 1. add (10) ;// (invalid) + This method is useful whenever we are performing only read operation. methodOne(ArrayList I); + Ifxisaclass then this method is applicable for ArrayList of either x type or its child classes. + Ifxcisan interface then this method is applicable for ArrayList of either x type or its implementation classes. + In this case also within the method we can't add anything to the List except null. 7/3 | DURGASOFT, #702, 2"Fioor HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Generics methodOne(ArrayList 1): Ifx1sa class then this method is applicable for ArrayList of either x type or its super classes. Ifx 1s 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: 12. 13 14 15 16. 17 18 19. 20. 24 22. 23. 24 ArrayListeString> I1=new Arraylist();//(valid) ArrayList I2=new ArrayListeString>();/1(valid) ArrayList I3=new ArrayList();//(valid) ArrayList |4=new ArrayList();/ /(valid) ArrayList? extends Number> IS=new ArrayList();(invalid) output: Compile time error. Test. java:10: incompatible types java.util ArrayList . Required: java.util.ArrayList ArrayList 15=new Arraylist() ; ArrayList I6=new ArrayList? extends Number>(); output: Compile time error Test.java:11: unexpected type found ? extends java.lang.Number required: class or interface without bounds ArrayList Lé=new ArrayList(); Arraylist I7=new ArrayList(); output: Test. java:12: unexpected type Found :? Required: class or interface without bounds ArrayList L7=new Arraylist<2>(); We can declare the type parameter either at class level or method le PEE ee class Testcr> { ) We can use anywhere this 'T'. PEE enone ec We have to declare just before return type. Example: public <1> void methodonel (T t){}//valid Public void methodone2(T t){}//valid 74 | DURGASOFT, #202, loor, HUDA Maitrivanam Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Generics public void methodOne3 (Tt) {}//valid Public void methodOned (T +) ()//valia Public void methodone(T t){}//invalid output: Compile time error. Test. java:7: interface expected here public void methodone(T t) {}//valid public void methodOne(T t){}//invalid outpu Compile time error. Test. java:8: interface expected here public void methodone(T t) ()//valid ommunication with non generic cod To provide compatibility with old version sun people compramized the concept of generies in very few area's the following is one such area. Example: import java-utél.+; class Test ( public static void main(String[] args) { ArrayList I-new ArrayList () ; Ladd ("A") ; //1.ada(10) ;//C.B:cannot find symbol ,method add (int) methodone (1) ; 1.add (10.5) ;//C.E:cannot find symbol method add (double) ) public static void methodone(ArrayList 1) { system.out.printin(1);//{A, 10, 10.5, true] 1.add (10) ; 2.add (10.5) ; Ladd (true) ; + 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=new Arraylist() ; ArrayList l=new ArrayList(); All are equal at runtime. ArrayList l=new ArrayList (); 75 | DURGASOFT, #202,2" Floor HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com Core Java with SCIP/ OCJP Notes By Durga Sir Generics Example import java.util.*; class Test { public static void main(String{] args) { ArrayList 1. add (10) 2.add (10.5); 1.add (true) ; System.out.printIn(1);// [10, 10.5, true] new ArrayList() ; } ) Example import java.util.*; class Test { public void methodone (ArrayList 1){} public void methodone (ArrayList 1) (} ) Output: Compile time error. Test. java:4: name clash: methodone (java.util .ArrayList) and me ‘thodOne (java.util. ArrayList) have the same public void methodone(ArrayList 1) {} + The following 2 declarations are equal. ArrayList ll=new ArrayList (); ArrayList 12=new ArrayList() ; + For these ArrayList objects we can add only String type of objects. Exampl 11 .add("A") ;//valia A1.add(10); //invalid 7 | DURGASOFT, #202,2" Floor RUDA Maitrivanam,Ameerpet, Hyderabad - 500038, ‘ 040 - 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com

You might also like