SlideShare a Scribd company logo
 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 strings
Kuntal Bhowmick
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
shafat6712
 
Intake 38 3
Intake 38 3Intake 38 3
Intake 38 3
Mahmoud Ouf
 
Net framework session01
Net framework session01Net framework session01
Net framework session01
Vivek chan
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
Julie 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.pdf
rajeshjangid1865
 
Java introduction
Java introductionJava introduction
Java introduction
Samsung Electronics Egypt
 
Lecture_7 Method Overloading.pptx
Lecture_7 Method Overloading.pptxLecture_7 Method Overloading.pptx
Lecture_7 Method Overloading.pptx
MaheenVohra
 
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
Kuntal Bhowmick
 
Intake 38 5
Intake 38 5Intake 38 5
Intake 38 5
Mahmoud Ouf
 
Chapter2pp
Chapter2ppChapter2pp
Chapter2ppJ. C.
 
03-Primitive-Datatypes.pdf
03-Primitive-Datatypes.pdf03-Primitive-Datatypes.pdf
03-Primitive-Datatypes.pdf
KaraBaesh
 
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 arrays
JayanthiM19
 

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

Latest trends in computer networking.pptx
Latest trends in computer networking.pptxLatest trends in computer networking.pptx
Latest trends in computer networking.pptx
JungkooksNonexistent
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
3ipehhoa
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
3ipehhoa
 
Bài tập unit 1 English in the world.docx
Bài tập unit 1 English in the world.docxBài tập unit 1 English in the world.docx
Bài tập unit 1 English in the world.docx
nhiyenphan2005
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
laozhuseo02
 
Comptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guideComptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guide
GTProductions1
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
laozhuseo02
 
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdfJAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
Javier Lasa
 
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdfMeet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Florence Consulting
 
This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!
nirahealhty
 
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
keoku
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
Arif0071
 
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
CIOWomenMagazine
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
Gal Baras
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
JeyaPerumal1
 
Italy Agriculture Equipment Market Outlook to 2027
Italy Agriculture Equipment Market Outlook to 2027Italy Agriculture Equipment Market Outlook to 2027
Italy Agriculture Equipment Market Outlook to 2027
harveenkaur52
 
guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...
Rogerio Filho
 
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC
 
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
ufdana
 
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
eutxy
 

Recently uploaded (20)

Latest trends in computer networking.pptx
Latest trends in computer networking.pptxLatest trends in computer networking.pptx
Latest trends in computer networking.pptx
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
 
Bài tập unit 1 English in the world.docx
Bài tập unit 1 English in the world.docxBài tập unit 1 English in the world.docx
Bài tập unit 1 English in the world.docx
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
 
Comptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guideComptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guide
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
 
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdfJAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
 
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdfMeet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
 
This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!This 7-second Brain Wave Ritual Attracts Money To You.!
This 7-second Brain Wave Ritual Attracts Money To You.!
 
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
一比一原版(SLU毕业证)圣路易斯大学毕业证成绩单专业办理
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
 
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
 
Italy Agriculture Equipment Market Outlook to 2027
Italy Agriculture Equipment Market Outlook to 2027Italy Agriculture Equipment Market Outlook to 2027
Italy Agriculture Equipment Market Outlook to 2027
 
guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...
 
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
 
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
 
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
 

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