SlideShare a Scribd company logo
1 of 33
 Creating a custom generic class
 Overview of generic programming,
 Creating generic classes using Object class and by not using
Object class,
 Creating generic methods,
 Creating generic interfaces,
 Using bounded types and WildCard
 Using the type inference diamond to create an object
Overview of generic programming
 The Java Generics programming is introduced in J2SE
5 to deal with type-safe objects.
 Before generics, we can store any type of objects in
collection i.e. non-generic.
 Now generics, forces the java programmer to store
specific type of objects.
In the simplest definition, generic programming is a
style of computer programming in which algorithms
are written in terms of to-be-specified-later types that
are then instantiated when needed for specific types
provided as parameters.
Advantage of Java Generics
There are mainly 3 advantages of generics.
They are as follows:
1) Type-safety :
1) We can hold only a single type of objects in generics.
2) It doesn’t allow to store other objects.
2) Type casting is not required:
1) There is no need to typecast the object.
Before Generics, we need to type cast.
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0); //typecasting
After Generics, we don't need to typecast the object.
List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0);
Advantage of Java Generics cont…
3) Compile-Time Checking:
1) It is checked at compile time so problem will not occur
at runtime.
2) The good programming strategy says it is far better to
handle the problem at compile time than runtime.
List<String> list = new ArrayList<String>();
list.add("hello");
list.add(32); //Compile Time Error
Example
class Gen<T>{
T ob;
Gen(T o){
ob = o;
}
T getob(){
return ob;
}
void showType(){
System.out.println("Type of T is " +ob.getClass().getName());
}
}
Example cont…
class GenDemo {
public static void main(String args[]){
Gen<Integer> iOb;
iOb = new Gen<Integer>(88);
iOb.showType();
int v = iOb.getob();
System.out.println("value: " + v);
Gen<String> strOb;
strOb = new Gen<String>("Generics Test");
strOb.showType();
String str = strOb.getob();
System.out.println("value: " + str);
}
}
Generics Work Only with Objects
 When declaring an instance of a generic type, the type
argument passed to the type parameter must be a class type.
Gen<int> strOb = new Gen<int>(53);
// Error, can't use primitive type
 A reference of one specific version of a generic type is not type
compatible with another version of the same generic type.
iOb = strOb; // Wrong!
Example using Object class
class NonGen {
Object ob;
NonGen(Object o) {
ob = o;
}
Object getob() {
return ob;
}
void showType() {
System.out.println("Type of ob is"+ob.getClass().getName());
}
}
Example using Object class cont…
class NonGenDemo {
public static void main(String args[]) {
NonGen iOb;
iOb = new NonGen(88);
iOb.showType();
int v = (Integer) iOb.getob();
System.out.println("value: " + v);
System.out.println();
NonGen strOb = new NonGen("Non-Generics Test");
strOb.showType();
String str = (String) strOb.getob();
System.out.println("value: " + str);
iOb = strOb;
v = (Integer) iOb.getob(); // run-time error!
}
}
Generic Class with
Multiple Type Parameters
class TwoGen<T, V> {
T ob1;
V ob2;
TwoGen(T o1, V o2) {
ob1 = o1;
ob2 = o2;
}
void showTypes() {
System.out.println("Type of T is " +ob1.getClass().getName());
System.out.println("Type of V is " +ob2.getClass().getName());
}
T getob1() {
return ob1;
}
V getob2() {
return ob2;
}
}
Generic Class with
Multiple Type Parameters cont…
class SimpGen {
public static void main(String args[]) {
TwoGen<Integer, String> t =
new TwoGen<Integer, String>(123, "Testing Two Parameter");
t.showTypes();
int v = t.getob1();
System.out.println("value: " + v);
String str = t.getob2();
System.out.println("value: " + str);
}
}
General Form of Generic Class
 The generics syntax for declaring a generic class:
class class-name<type-param-list>
{ // ... }
 The syntax for declaring a reference to a generic class:
class-name<type-arg-list> var-name =
new class-name<type-arg-list>(cons-arg-list);
Problem
Create a generic class that contains a method that returns
the average of an array of numbers of any type, including
integers, floats, and doubles.
Possible Solution
class Stats<T> {
T[] nums;
Stats(T[] o) {
nums = o;
}
double average() {
double sum = 0.0;
for(int i=0; i < nums.length; i++)
sum += nums[i].doubleValue(); // Error!!!
return sum / nums.length;
}
}
Why Error?
 The compiler has no way to know that you are intending to
create Stats objects using only numeric types.
 When we try to compile Stats, an error is reported that
indicates that the doubleValue( ) method is unknown.
 We need some way to tell the compiler that we intend to pass
only numeric types to T.
Bounded Types
 Used to limit the types that can be passed to a type parameter.
 When specifying a type parameter, we can create an upper bound
that declares the super-class from which all type arguments must be
derived.
<T extends superclass>
 A bound can include both a class type and one or more interfaces.
class Gen<T extends MyClass & MyInterface>
 Any type argument passed to T must be a subclass of MyClass and
implement MyInterface.[TestAverageModified.java[Demo Program]]
Solution with No Error:
class Stats<T extends Number > {
T[] nums;
Stats(T[] o) {
nums = o;
}
double average() {
double sum = 0.0;
for(int i=0; i < nums.length; i++)
sum += nums[i].doubleValue(); // No Error!!!
return sum / nums.length;
}
}
Solution with No Error: cont…
class BoundsDemo {
public static void main(String args[]) {
Integer inums[] = { 1, 2, 3, 4, 5 };
Stats<Integer> iob = new Stats<Integer>(inums);
double v = iob.average();
System.out.println("iob average is " + v);
Double dnums[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
Stats<Double> dob = new Stats<Double>(dnums);
double w = dob.average();
System.out.println("dob average is " + w);
}
}
Problem
 Create a generic class that contains a method sameAvg()
that determines if two Stats objects contain arrays that
yield the same average, no matter what type of numeric
data each object holds.
 For example, if one object contains the double values 1.0,
2.0, and 3.0, and the other object contains the integer
values 2, 1, and 3, then the averages will be the same.
Possible Solution
Integer inums[] = { 1, 2, 3, 4 };
Double dnums[] = { 1.1, 2.2, 3.3, 4.4 };
Stats<Integer> iob = new Stats<Integer>(inums);
Stats<Double> dob = new Stats<Double>(dnums);
if(iob.sameAvg(dob))
System.out.println("Averages are the same.");
else
System.out.println("Averages differ.");
boolean sameAvg(Stats<T> ob)
{
if(average() == ob.average())
return true;
return false;
}
Why Error?
 It will work only with the objects of same type.
 if the invoking object is of type Stats<Integer>, then the
parameter ob must also be of type Stats<Integer>.
WildCard Argument
 The wildcard simply matches the validity of object.
 The wildcard argument is specified by the ?, and it represents an unknown
type.
boolean sameAvg(Stats<?> ob)
{
if(average() == ob.average())
return true;
return false;
}
Important: It is important to understand that the wildcard does not affect
what type of Stats objects can be created. This is governed by the extends
clause in the Stats declaration. The wildcard simply matches any valid Stats
object.
Generic methods
 It is possible to declare a generic method that uses one or more
type parameters.
 Methods inside a generic class are automatically generic
relative to the type parameters.
 It is possible to create a generic method that is enclosed within
a non-generic class.
Generic methods cont…
 The type parameters are declared before the return type of the
method.
 Generic methods can be either static or non-static.
<type-param-list> ret-type method-name(param-list) {…}
 Example:
public static <V, T extends V> boolean isIn(V value, T[] array)
 This ability to enforce type safety is one of the most important
advantages of generic methods.
Example:
class GenMethDemo{
public static <V, T extends V> boolean isIn(V value, T[] array){
for(int i=0;i<array.length;i++){
if(value.equals(array[i]))
return true;
}
return false;
}
public static void main(String[] args){
Integer i[]={1,2,3,4,5,6};
System.out.println("2 is in Integer Array"+isIn(2,i));
String s[]={"one","two","three","four","five","six"};
System.out.println("one is in String Array"+isIn("one",s));
}
}
Generic Interfaces
 Generic interfaces are specified just like generic classes.
Example:
interface MinMax<T extends Comparable<T>>
{ T min(); T max(); }
 The implementing class must specify the same bound.
 Once the bound has been established, it need not to be
specified again in the implements clause.
Generic Interfaces cont…
 class MyClass<T extends Comparable<T>> implements MinMax <T extends
Comparable<T>> { //Wrong
 In general, if a class implements a generic interface, then that class must also
be generic, at least to the extent that it takes a type parameter that is passed to
the interface. For example, the following attempt to declare MyClass is in
error:
 class MyClass implements MinMax<T> { // Wrong!
 Because MyClass does not declare a type parameter, there is no way to pass one
to MinMax. In this case, the identifier T is simply unknown, and the compiler
reports an error. Of course, if a class implements a specific type of generic
interface, such as shown here:
 class MyClass implements MinMax<Integer> { // OK
Generic Interfaces cont…
interface MinMax<T extends Comparable<T>> {
T min();
T max();
}
class My<T extends Comparable<T>> implements
MinMax<T> {
…
}
Type inference diamond to
create an object
Without Type inference diamond to create an object:
Gen<Integer> iOb = new Gen<Integer>(88);
With Type inference diamond to create an object:
Gen<Integer> iOb = new Gen< >(88);
 .doubleValue():method convert object into primitive
double (unboxing)
 Boxing: conversion primitive data type into object.
 Integer.parseInt(): Converion string into int
 toString(): object to String
 Before JDK5 : Comparable interface return
object.(need typecasting required,type safety less,
compile error checking)
 After JDK5 version solve all the above problems and
we can make it genric.
 T - Type
 E - Element
 K - Key
 N - Number
 V - Value
Thank You

More Related Content

Similar to GenericsFinal.ppt

Javase5generics
Javase5genericsJavase5generics
Javase5genericsimypraz
 
Class notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsClass notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsKuntal Bhowmick
 
Net framework session01
Net framework session01Net framework session01
Net framework session01Vivek chan
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Create a menu-driven program that will accept a collection of non-ne.pdf
Create a menu-driven program that will accept a collection of non-ne.pdfCreate a menu-driven program that will accept a collection of non-ne.pdf
Create a menu-driven program that will accept a collection of non-ne.pdfrajeshjangid1865
 
Lecture_7 Method Overloading.pptx
Lecture_7 Method Overloading.pptxLecture_7 Method Overloading.pptx
Lecture_7 Method Overloading.pptxMaheenVohra
 
Class notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsClass notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsKuntal Bhowmick
 
Chapter2pp
Chapter2ppChapter2pp
Chapter2ppJ. C.
 
03-Primitive-Datatypes.pdf
03-Primitive-Datatypes.pdf03-Primitive-Datatypes.pdf
03-Primitive-Datatypes.pdfKaraBaesh
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Andrew Petryk
 
arrays in c# including Classes handling arrays
arrays in c#  including Classes handling arraysarrays in c#  including Classes handling arrays
arrays in c# including Classes handling arraysJayanthiM19
 

Similar to GenericsFinal.ppt (20)

Javase5generics
Javase5genericsJavase5generics
Javase5generics
 
Struktur data 1
Struktur data 1Struktur data 1
Struktur data 1
 
Class notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsClass notes(week 4) on arrays and strings
Class notes(week 4) on arrays and strings
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
 
Intake 38 3
Intake 38 3Intake 38 3
Intake 38 3
 
9 Arrays
9 Arrays9 Arrays
9 Arrays
 
Net framework session01
Net framework session01Net framework session01
Net framework session01
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Create a menu-driven program that will accept a collection of non-ne.pdf
Create a menu-driven program that will accept a collection of non-ne.pdfCreate a menu-driven program that will accept a collection of non-ne.pdf
Create a menu-driven program that will accept a collection of non-ne.pdf
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
Java generics final
Java generics finalJava generics final
Java generics final
 
Java introduction
Java introductionJava introduction
Java introduction
 
Collections
CollectionsCollections
Collections
 
Lecture_7 Method Overloading.pptx
Lecture_7 Method Overloading.pptxLecture_7 Method Overloading.pptx
Lecture_7 Method Overloading.pptx
 
Class notes(week 4) on arrays and strings
Class notes(week 4) on arrays and stringsClass notes(week 4) on arrays and strings
Class notes(week 4) on arrays and strings
 
Intake 38 5
Intake 38 5Intake 38 5
Intake 38 5
 
Chapter2pp
Chapter2ppChapter2pp
Chapter2pp
 
03-Primitive-Datatypes.pdf
03-Primitive-Datatypes.pdf03-Primitive-Datatypes.pdf
03-Primitive-Datatypes.pdf
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
 
arrays in c# including Classes handling arrays
arrays in c#  including Classes handling arraysarrays in c#  including Classes handling arrays
arrays in c# including Classes handling arrays
 

Recently uploaded

Nanded City ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready ...
Nanded City ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready ...Nanded City ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready ...
Nanded City ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready ...tanu pandey
 
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...Diya Sharma
 
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersMoving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersDamian Radcliffe
 
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service AvailableCall Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service AvailableSeo
 
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
CALL ON ➥8923113531 🔝Call Girls Lucknow Lucknow best sexual service Online
CALL ON ➥8923113531 🔝Call Girls Lucknow Lucknow best sexual service OnlineCALL ON ➥8923113531 🔝Call Girls Lucknow Lucknow best sexual service Online
CALL ON ➥8923113531 🔝Call Girls Lucknow Lucknow best sexual service Onlineanilsa9823
 
How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)Damian Radcliffe
 
Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$kojalkojal131
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...Neha Pandey
 
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663Call Girls Mumbai
 
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...tanu pandey
 
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 

Recently uploaded (20)

Nanded City ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready ...
Nanded City ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready ...Nanded City ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready ...
Nanded City ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready ...
 
VVVIP Call Girls In Connaught Place ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In Connaught Place ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...VVVIP Call Girls In Connaught Place ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In Connaught Place ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
 
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
 
Rohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
 
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersMoving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
 
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service AvailableCall Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
 
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
 
CALL ON ➥8923113531 🔝Call Girls Lucknow Lucknow best sexual service Online
CALL ON ➥8923113531 🔝Call Girls Lucknow Lucknow best sexual service OnlineCALL ON ➥8923113531 🔝Call Girls Lucknow Lucknow best sexual service Online
CALL ON ➥8923113531 🔝Call Girls Lucknow Lucknow best sexual service Online
 
Russian Call Girls in %(+971524965298 )# Call Girls in Dubai
Russian Call Girls in %(+971524965298  )#  Call Girls in DubaiRussian Call Girls in %(+971524965298  )#  Call Girls in Dubai
Russian Call Girls in %(+971524965298 )# Call Girls in Dubai
 
How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)
 
@9999965857 🫦 Sexy Desi Call Girls Laxmi Nagar 💓 High Profile Escorts Delhi 🫶
@9999965857 🫦 Sexy Desi Call Girls Laxmi Nagar 💓 High Profile Escorts Delhi 🫶@9999965857 🫦 Sexy Desi Call Girls Laxmi Nagar 💓 High Profile Escorts Delhi 🫶
@9999965857 🫦 Sexy Desi Call Girls Laxmi Nagar 💓 High Profile Escorts Delhi 🫶
 
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Ashram Chowk Delhi 💯Call Us 🔝8264348440🔝
 
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
 
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
 
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
 
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
 
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 

GenericsFinal.ppt

  • 1.  Creating a custom generic class  Overview of generic programming,  Creating generic classes using Object class and by not using Object class,  Creating generic methods,  Creating generic interfaces,  Using bounded types and WildCard  Using the type inference diamond to create an object
  • 2. Overview of generic programming  The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.  Before generics, we can store any type of objects in collection i.e. non-generic.  Now generics, forces the java programmer to store specific type of objects.
  • 3. In the simplest definition, generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters.
  • 4. Advantage of Java Generics There are mainly 3 advantages of generics. They are as follows: 1) Type-safety : 1) We can hold only a single type of objects in generics. 2) It doesn’t allow to store other objects. 2) Type casting is not required: 1) There is no need to typecast the object. Before Generics, we need to type cast. List list = new ArrayList(); list.add("hello"); String s = (String) list.get(0); //typecasting After Generics, we don't need to typecast the object. List<String> list = new ArrayList<String>(); list.add("hello"); String s = list.get(0);
  • 5. Advantage of Java Generics cont… 3) Compile-Time Checking: 1) It is checked at compile time so problem will not occur at runtime. 2) The good programming strategy says it is far better to handle the problem at compile time than runtime. List<String> list = new ArrayList<String>(); list.add("hello"); list.add(32); //Compile Time Error
  • 6. Example class Gen<T>{ T ob; Gen(T o){ ob = o; } T getob(){ return ob; } void showType(){ System.out.println("Type of T is " +ob.getClass().getName()); } }
  • 7. Example cont… class GenDemo { public static void main(String args[]){ Gen<Integer> iOb; iOb = new Gen<Integer>(88); iOb.showType(); int v = iOb.getob(); System.out.println("value: " + v); Gen<String> strOb; strOb = new Gen<String>("Generics Test"); strOb.showType(); String str = strOb.getob(); System.out.println("value: " + str); } }
  • 8. Generics Work Only with Objects  When declaring an instance of a generic type, the type argument passed to the type parameter must be a class type. Gen<int> strOb = new Gen<int>(53); // Error, can't use primitive type  A reference of one specific version of a generic type is not type compatible with another version of the same generic type. iOb = strOb; // Wrong!
  • 9. Example using Object class class NonGen { Object ob; NonGen(Object o) { ob = o; } Object getob() { return ob; } void showType() { System.out.println("Type of ob is"+ob.getClass().getName()); } }
  • 10. Example using Object class cont… class NonGenDemo { public static void main(String args[]) { NonGen iOb; iOb = new NonGen(88); iOb.showType(); int v = (Integer) iOb.getob(); System.out.println("value: " + v); System.out.println(); NonGen strOb = new NonGen("Non-Generics Test"); strOb.showType(); String str = (String) strOb.getob(); System.out.println("value: " + str); iOb = strOb; v = (Integer) iOb.getob(); // run-time error! } }
  • 11. Generic Class with Multiple Type Parameters class TwoGen<T, V> { T ob1; V ob2; TwoGen(T o1, V o2) { ob1 = o1; ob2 = o2; } void showTypes() { System.out.println("Type of T is " +ob1.getClass().getName()); System.out.println("Type of V is " +ob2.getClass().getName()); } T getob1() { return ob1; } V getob2() { return ob2; } }
  • 12. Generic Class with Multiple Type Parameters cont… class SimpGen { public static void main(String args[]) { TwoGen<Integer, String> t = new TwoGen<Integer, String>(123, "Testing Two Parameter"); t.showTypes(); int v = t.getob1(); System.out.println("value: " + v); String str = t.getob2(); System.out.println("value: " + str); } }
  • 13. General Form of Generic Class  The generics syntax for declaring a generic class: class class-name<type-param-list> { // ... }  The syntax for declaring a reference to a generic class: class-name<type-arg-list> var-name = new class-name<type-arg-list>(cons-arg-list);
  • 14. Problem Create a generic class that contains a method that returns the average of an array of numbers of any type, including integers, floats, and doubles.
  • 15. Possible Solution class Stats<T> { T[] nums; Stats(T[] o) { nums = o; } double average() { double sum = 0.0; for(int i=0; i < nums.length; i++) sum += nums[i].doubleValue(); // Error!!! return sum / nums.length; } }
  • 16. Why Error?  The compiler has no way to know that you are intending to create Stats objects using only numeric types.  When we try to compile Stats, an error is reported that indicates that the doubleValue( ) method is unknown.  We need some way to tell the compiler that we intend to pass only numeric types to T.
  • 17. Bounded Types  Used to limit the types that can be passed to a type parameter.  When specifying a type parameter, we can create an upper bound that declares the super-class from which all type arguments must be derived. <T extends superclass>  A bound can include both a class type and one or more interfaces. class Gen<T extends MyClass & MyInterface>  Any type argument passed to T must be a subclass of MyClass and implement MyInterface.[TestAverageModified.java[Demo Program]]
  • 18. Solution with No Error: class Stats<T extends Number > { T[] nums; Stats(T[] o) { nums = o; } double average() { double sum = 0.0; for(int i=0; i < nums.length; i++) sum += nums[i].doubleValue(); // No Error!!! return sum / nums.length; } }
  • 19. Solution with No Error: cont… class BoundsDemo { public static void main(String args[]) { Integer inums[] = { 1, 2, 3, 4, 5 }; Stats<Integer> iob = new Stats<Integer>(inums); double v = iob.average(); System.out.println("iob average is " + v); Double dnums[] = { 1.1, 2.2, 3.3, 4.4, 5.5 }; Stats<Double> dob = new Stats<Double>(dnums); double w = dob.average(); System.out.println("dob average is " + w); } }
  • 20. Problem  Create a generic class that contains a method sameAvg() that determines if two Stats objects contain arrays that yield the same average, no matter what type of numeric data each object holds.  For example, if one object contains the double values 1.0, 2.0, and 3.0, and the other object contains the integer values 2, 1, and 3, then the averages will be the same.
  • 21. Possible Solution Integer inums[] = { 1, 2, 3, 4 }; Double dnums[] = { 1.1, 2.2, 3.3, 4.4 }; Stats<Integer> iob = new Stats<Integer>(inums); Stats<Double> dob = new Stats<Double>(dnums); if(iob.sameAvg(dob)) System.out.println("Averages are the same."); else System.out.println("Averages differ."); boolean sameAvg(Stats<T> ob) { if(average() == ob.average()) return true; return false; }
  • 22. Why Error?  It will work only with the objects of same type.  if the invoking object is of type Stats<Integer>, then the parameter ob must also be of type Stats<Integer>.
  • 23. WildCard Argument  The wildcard simply matches the validity of object.  The wildcard argument is specified by the ?, and it represents an unknown type. boolean sameAvg(Stats<?> ob) { if(average() == ob.average()) return true; return false; } Important: It is important to understand that the wildcard does not affect what type of Stats objects can be created. This is governed by the extends clause in the Stats declaration. The wildcard simply matches any valid Stats object.
  • 24. Generic methods  It is possible to declare a generic method that uses one or more type parameters.  Methods inside a generic class are automatically generic relative to the type parameters.  It is possible to create a generic method that is enclosed within a non-generic class.
  • 25. Generic methods cont…  The type parameters are declared before the return type of the method.  Generic methods can be either static or non-static. <type-param-list> ret-type method-name(param-list) {…}  Example: public static <V, T extends V> boolean isIn(V value, T[] array)  This ability to enforce type safety is one of the most important advantages of generic methods.
  • 26. Example: class GenMethDemo{ public static <V, T extends V> boolean isIn(V value, T[] array){ for(int i=0;i<array.length;i++){ if(value.equals(array[i])) return true; } return false; } public static void main(String[] args){ Integer i[]={1,2,3,4,5,6}; System.out.println("2 is in Integer Array"+isIn(2,i)); String s[]={"one","two","three","four","five","six"}; System.out.println("one is in String Array"+isIn("one",s)); } }
  • 27. Generic Interfaces  Generic interfaces are specified just like generic classes. Example: interface MinMax<T extends Comparable<T>> { T min(); T max(); }  The implementing class must specify the same bound.  Once the bound has been established, it need not to be specified again in the implements clause.
  • 28. Generic Interfaces cont…  class MyClass<T extends Comparable<T>> implements MinMax <T extends Comparable<T>> { //Wrong  In general, if a class implements a generic interface, then that class must also be generic, at least to the extent that it takes a type parameter that is passed to the interface. For example, the following attempt to declare MyClass is in error:  class MyClass implements MinMax<T> { // Wrong!  Because MyClass does not declare a type parameter, there is no way to pass one to MinMax. In this case, the identifier T is simply unknown, and the compiler reports an error. Of course, if a class implements a specific type of generic interface, such as shown here:  class MyClass implements MinMax<Integer> { // OK
  • 29. Generic Interfaces cont… interface MinMax<T extends Comparable<T>> { T min(); T max(); } class My<T extends Comparable<T>> implements MinMax<T> { … }
  • 30. Type inference diamond to create an object Without Type inference diamond to create an object: Gen<Integer> iOb = new Gen<Integer>(88); With Type inference diamond to create an object: Gen<Integer> iOb = new Gen< >(88);
  • 31.  .doubleValue():method convert object into primitive double (unboxing)  Boxing: conversion primitive data type into object.  Integer.parseInt(): Converion string into int  toString(): object to String  Before JDK5 : Comparable interface return object.(need typecasting required,type safety less, compile error checking)  After JDK5 version solve all the above problems and we can make it genric.
  • 32.  T - Type  E - Element  K - Key  N - Number  V - Value