Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
211 views

Generics in Java - Javatpoint

This document discusses generics in Java. Generics were introduced in Java 5 to allow type-safe objects in collections. Generics provide type safety, eliminate casting, and allow compile-time type checking. The document provides examples of using generics with collections like ArrayList and maps. It also discusses generic classes, methods, and wildcards.

Uploaded by

MalliKarjun
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
211 views

Generics in Java - Javatpoint

This document discusses generics in Java. Generics were introduced in Java 5 to allow type-safe objects in collections. Generics provide type safety, eliminate casting, and allow compile-time type checking. The document provides examples of using generics with collections like ArrayList and maps. It also discusses generic classes, methods, and wildcards.

Uploaded by

MalliKarjun
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

2017531 GenericsinJavajavatpoint

GenericsinJava
TheJavaGenerics programming is introduced in J2SE 5 to deal with
typesafeobjects.

Before generics, we can store any type of objects in collection i.e.


nongeneric. Now generics, forces the java programmer to store
specifictypeofobjects.

AdvantageofJavaGenerics

Therearemainly3advantagesofgenerics.Theyareasfollows:

1) Typesafety : We can hold only a single type of objects in


generics.Itdoesntallowtostoreotherobjects.

2) Type casting is not required: There is no need to typecast the


object.

BeforeGenerics,weneedtotypecast.

1. Listlist=newArrayList()

2. list.add("hello")

3. Strings=(String)list.get(0)//typecasting

AfterGenerics,wedon'tneedtotypecasttheobject.

1. List<String>list=newArrayList<String>()

2. list.add("hello")

3. Strings=list.get(0)

3)CompileTimeChecking:Itischeckedatcompiletimesoproblem
will not occur at runtime. The good programming strategy says it is
farbettertohandletheproblematcompiletimethanruntime.

1. List<String>list=newArrayList<String>()

2. list.add("hello")

3. list.add(32)//CompileTimeError

Syntaxtousegenericcollection

1. ClassOrInterface<Type>

https://www.javatpoint.com/genericsinjava 1/7
2017531 GenericsinJavajavatpoint

ExampletouseGenericsinjava

1. ArrayList<String>

FullExampleofGenericsinJava
Here,weareusingtheArrayListclass,butyoucanuseanycollection
class such as ArrayList, LinkedList, HashSet, TreeSet, HashMap,
Comparatoretc.

1. importjava.util.*

2. classTestGenerics1{

3. publicstaticvoidmain(Stringargs[]){

4. ArrayList<String>list=newArrayList<String>()

5. list.add("rahul")

6. list.add("jai")

7. //list.add(32)//compiletimeerror

8.

9. Strings=list.get(1)//typecastingisnotrequired

10. System.out.println("elementis:"+s)

11.

12. Iterator<String>itr=list.iterator()

13. while(itr.hasNext()){

14. System.out.println(itr.next())

15. }

16. }

17. }

TestitNow

Output:elementis:jai
rahul
jai

ExampleofJavaGenericsusingMap
Now we are going to use map elements using generics. Here, we
need to pass key and value. Let us understand it by a simple
example:

https://www.javatpoint.com/genericsinjava 2/7
2017531 GenericsinJavajavatpoint

1. importjava.util.*

2. classTestGenerics2{

3. publicstaticvoidmain(Stringargs[]){

4. Map<Integer,String>map=newHashMap<Integer,String>()

5. map.put(1,"vijay")

6. map.put(4,"umesh")

7. map.put(2,"ankit")

8.

9. //NowuseMap.EntryforSetandIterator

10. Set<Map.Entry<Integer,String>>set=map.entrySet()

11.

12. Iterator<Map.Entry<Integer,String>>itr=set.iterator()

13. while(itr.hasNext()){

14. Map.Entrye=itr.next()//noneedtotypecast

15. System.out.println(e.getKey()+""+e.getValue())

16. }

17.

18. }}

TestitNow

Output:1vijay
2ankit
4umesh

Genericclass
Aclassthatcanrefertoanytypeisknownasgenericclass.Here,we
are using T type parameter to create the generic class of specific
type.

Letsseethesimpleexampletocreateandusethegenericclass.

Creatinggenericclass:

1. classMyGen<T>{

2. Tobj

3. voidadd(Tobj){this.obj=obj}

4. Tget(){returnobj}

5. }

https://www.javatpoint.com/genericsinjava 3/7
2017531 GenericsinJavajavatpoint

TheTtypeindicatesthatitcanrefertoanytype(likeString,Integer,
Employee etc.). The type you specify for the class, will be used to
storeandretrievethedata.

Usinggenericclass:

Letsseethecodetousethegenericclass.

1. classTestGenerics3{

2. publicstaticvoidmain(Stringargs[]){

3. MyGen<Integer>m=newMyGen<Integer>()

4. m.add(2)

5. //m.add("vivek")//Compiletimeerror

6. System.out.println(m.get())

7. }}

Output:2

TypeParameters
The type parameters naming conventions are important to learn
genericsthoroughly.Thecommonlytypeparametersareasfollows:

1.TType

2.EElement

3.KKey

4.NNumber

5.VValue

GenericMethod
Likegenericclass,wecancreategenericmethodthatcanacceptany
typeofargument.

Lets see a simple example of java generic method to print array


elements.WeareusinghereEtodenotetheelement.

1. publicclassTestGenerics4{

2.

3. publicstatic<E>voidprintArray(E[]elements){

4. for(Eelement:elements){

5. System.out.println(element)
https://www.javatpoint.com/genericsinjava 4/7
2017531 GenericsinJavajavatpoint

6. }

7. System.out.println()

8. }

9. publicstaticvoidmain(Stringargs[]){

10. Integer[]intArray={10,20,30,40,50}

11. Character[]charArray={'J','A','V','A','T','P','O','I','N','T'}

12.

13. System.out.println("PrintingIntegerArray")

14. printArray(intArray)

15.

16. System.out.println("PrintingCharacterArray")

17. printArray(charArray)

18. }

19. }

TestitNow

Output:PrintingIntegerArray
10
20
30
40
50
PrintingCharacterArray
J
A
V
A
T
P
O
I
N
T

WildcardinJavaGenerics
The ? (question mark) symbol represents wildcard element. It means
any type. If we write <? extends Number>, it means any child class
ofNumbere.g.Integer,Float,doubleetc.Nowwecancallthemethod
ofNumberclassthroughanychildclassobject.

https://www.javatpoint.com/genericsinjava 5/7
2017531 GenericsinJavajavatpoint

Let'sunderstanditbytheexamplegivenbelow:

1. importjava.util.*

2. abstractclassShape{

3. abstractvoiddraw()

4. }

5. classRectangleextendsShape{

6. voiddraw(){System.out.println("drawingrectangle")}

7. }

8. classCircleextendsShape{

9. voiddraw(){System.out.println("drawingcircle")}

10. }

11.

12.

13. classGenericTest{

14. //creatingamethodthatacceptsonlychildclassofShape

15. publicstaticvoiddrawShapes(List<?extendsShape>lists){

16. for(Shapes:lists){

17. s.draw()//callingmethodofShapeclassbychildclassinstance

18. }

19. }

20. publicstaticvoidmain(Stringargs[]){

21. List<Rectangle>list1=newArrayList<Rectangle>()

22. list1.add(newRectangle())

23.

24. List<Circle>list2=newArrayList<Circle>()

25. list2.add(newCircle())

26. list2.add(newCircle())

27.

28. drawShapes(list1)

29. drawShapes(list2)

30. }}

drawingrectangle
drawingcircle
drawingcircle

<<prev next>>
https://www.javatpoint.com/genericsinjava 6/7
2017531 GenericsinJavajavatpoint

Sharethispage

Latest4Tutorials

CouchDB Docker

Rails RichFaces

https://www.javatpoint.com/genericsinjava 7/7

You might also like