Generics and collections in Java

ergurpreet123 1,153 views 19 slides Jan 11, 2018
Slide 1
Slide 1 of 19
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19

About This Presentation

Generic programming is a style of computer programming in which algorithms are written in terms of types to-be-specified-later that are then instantiated when needed for specific types provided as parameters.

Generics are a facility of generic programming that were added to the Java p...


Slide Content

GenericsandCollections
Visit http://gsbprogramming.blogspot.in

Genericprogrammingisastyleofcomputerprogramminginwhichalgorithmsare
writtenintermsoftypesto-be-specified-laterthataretheninstantiatedwhen
neededforspecifictypesprovidedasparameters.
GenericsareafacilityofgenericprogrammingthatwereaddedtotheJava
programminglanguagein2004withinversionJ2SE5.0.Theyweredesignedto
extendJava'stypesystemtoallow“atypeormethodtooperateonobjectsof
varioustypeswhileprovidingcompile-timetypesafety”
TheJavacollectionsframeworksupportsgenericstospecifythetypeofobjects
storedinacollectioninstance.

AccordingtoJavaLanguageSpecification:
1.Atypevariableisanunqualifiedidentifier.Typevariablesareintroducedbygenericclass
declarations,genericinterfacedeclarations,genericmethoddeclarations,andbygeneric
constructordeclarations.
2.Aclassisgenericifitdeclaresoneormoretypevariables.Thesetypevariablesareknownasthetype
parametersoftheclass.Itdefinesoneormoretypevariablesthatactasparameters.Agenericclass
declarationdefinesasetofparameterizedtypes,oneforeachpossibleinvocationofthetype
parametersection.Alloftheseparameterizedtypessharethesameclassatruntime.
3.Aninterfaceisgenericifitdeclaresoneormoretypevariables.Thesetypevariablesareknownasthe
typeparametersoftheinterface.Itdefinesoneormoretypevariablesthatactasparameters.A
genericinterfacedeclarationdefinesasetoftypes,oneforeachpossibleinvocationofthetype
parametersection.Allparameterizedtypessharethesameinterfaceatruntime.
4.Amethodisgenericifitdeclaresoneormoretypevariables.Thesetypevariablesareknownasthe
formaltypeparametersofthemethod.Theformoftheformaltypeparameterlistisidenticaltoatype
parameterlistofaclassorinterface.
5.Aconstructorcanbedeclaredasgeneric,independentlyofwhethertheclassthattheconstructoris
declaredinisitselfgeneric.Aconstructorisgenericifitdeclaresoneormoretypevariables.These
typevariablesareknownastheformaltypeparametersoftheconstructor.Theformoftheformal
typeparameterlistisidenticaltoatypeparameterlistofagenericclassorinterface.

Consider the following example:
Although the code is compiled without error, it throws a runtime exception (java.lang.ClassCastException) when
executing the second last statement of code. This type of problem can be avoided by using generics

With Generics:
Compiling this fragment with J2SE 5.0 (or later) will yield acompile-timeerror because the
compiler will detect thatlist.get(2)returnsStringinstead ofInteger

Entry<String, String> grade = newEntry<String, String>("Mike", "A");
Entry<String, Integer> mark = newEntry<String, Integer>("Mike", 100);
System.out.println("grade: " + grade);
System.out.println("mark: " + mark);
Entry<Integer, Boolean> prime =
newEntry<>(13, true); //Diamond Operator
if(prime.getValue())
System.out.println(prime.getKey() + " is prime.");
else
System.out.println(prime.getKey() + " is not prime.");
Output:
grade: (Mike, A)
mark: (Mike, 100)
13 is prime.

Note: If we remove the first<Type>in the above method, we will get compilation
error (cannot find symbol 'Type') since it represents the declaration of the symbol.
In many cases the user of the method need not indicate the type parameters, as
they can be inferred:
Entry<String, String> pair = Entry.twice("Hello");
The parameters can be explicitly added if needed:
Entry<String, String> pair = Entry.<String>twice("Hello");

Output:
java.lang.Integer= 11
java.lang.String= GeeksForGeeks
java.lang.Double= 1.0

Programs that uses Generics has got many benefits over non-generic code.
1.Code Reuse: We can write a method/class/interface once and use for any type we want.
2.Type Safety : Generics make errors to appear compile time than at run time (It’s always
better to know problems in your code at compile time rather than making your code fail
at run time).
3.Individual Type Casting is not required
ArrayList<String> al= new ArrayList<String> ();
al.add(“Gurpreet");
// Typecasting is not needed
String s1 = al.get(0);
4. Implementing generic algorithms: By using generics, we can implement algorithms that
work on different types of objects and at the same they are type safe too.

What is Collection in java?
Collection represents a single unit of objects i.e. a group.
What is framework in java?
•provides readymade architecture.
•represents set of classes and interface.
•is optional.
What is Collection framework?
Collection framework represents a unified architecture for storing and manipulating group of
objects. It has:
•Interfaces and its implementations i.e. classes
•Algorithm

JavaArrayListclassusesadynamicarrayforstoringtheelements.Itinherits
AbstractListclassandimplementsListinterface.
TheimportantpointsaboutJavaArrayListclassare:
•JavaArrayListclasscancontainduplicateelements.
•JavaArrayListclassmaintainsinsertionorder.
•JavaArrayListclassisnonsynchronized.
•JavaArrayListallowsrandomaccessbecausearrayworksattheindexbasis.
•InJavaArrayListclass,manipulationisslowbecausealotofshiftingneedsto
beoccurredifanyelementisremovedfromthearraylist.

JavaLinkedListclassusesdoublylinkedlisttostoretheelements.Itprovidesa
linked-listdatastructure.ItinheritstheAbstractListclassandimplementsList
andDequeinterfaces.
TheimportantpointsaboutJavaLinkedListare:
•JavaLinkedListclasscancontainduplicateelements.
•JavaLinkedListclassmaintainsinsertionorder.
•JavaLinkedListclassisnonsynchronized.
•InJavaLinkedListclass,manipulationisfastbecausenoshiftingneedsto
beoccurred.
•JavaLinkedListclasscanbeusedaslist,stackorqueue.

JavaHashMapclassimplementsthemapinterfacebyusingahashtable.It
inheritsAbstractMapclassandimplementsMapinterface.
TheimportantpointsaboutJavaHashMapclassare:
•AHashMapcontainsvaluesbasedonthekey.
•Itcontainsonlyuniqueelements.
•Itmayhaveonenullkeyandmultiplenullvalues.
•Itmaintainsnoorder.

FormoreVisit:
http://gsb-programming.blogspot.in/search/label/Java