SlideShare ist ein Scribd-Unternehmen logo
1 von 42
Downloaden Sie, um offline zu lesen
Advanced Java Programming
Topic: Generics
By
Ravi Kant Sahu
Asst. Professor, LPU
Contents
 Introduction
 Benefits of Generics
 Generic Classes and Interfaces
 Generic Methods
 Wildcard Generic Types
 Restrictions on Generics
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Introduction
 Enables to create classes, interfaces, and methods in which
the type of data upon which they operate is specified as a
parameter.
 Introduced in Java by jdk 1.5.
 Generics means parameterized types.
 Generics add the type-safety.
 Generics add stability to your code by making more of
your bugs detectable at compile time.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Why Generics?
 The functionality of Gen class can be achieved without
generics by specifying Object type and using proper
casting whenever required.
Then why we use Generics?
 Java compiler does not have knowledge about the type of
data actually stored in NonGen. So-
 Explicit casts must be employed to retrieve the stored data.
 Several type mismatch errors cannot be found until run time.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Why Generics?
 Stronger type checks at compile time
 Elimination of casts
List list = new ArrayList(); list.add("hello");
String s = (String) list.get(0);
 Using generics:
List<String> list = new ArrayList<String>(); list.add("hello");
String s = list.get(0); // no cast
 Enabling programmers to implement generic algorithms.
We can implement generic algorithms that work on collections of
different types, can be customized, and are type safe and easier to
read.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Advantage of Generics
 The ability to create type-safe code in which type-
mismatch errors are caught at compile time is a key
advantage of generics.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
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());
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
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 = new Gen<String>("Generics
Test");
strOb.showType();
String str = strOb.getob();
System.out.println("value: " + str);
} }
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
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);
 The above declaration is an error.
 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!
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Generic class
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
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);
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
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; }
 }
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class SimpGen {
public static void main(String args[]) {
TwoGen<Integer, String> t =
new TwoGen<Integer, String>(16920, "Ravi
Kant");
t.showTypes();
int v = t.getob1();
System.out.println("value: " + v);
String str = t.getob2();
System.out.println("value: " + str);
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
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.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
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;
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
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.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
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>
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
WILD CARD GeneRICS
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
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.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
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 same_Avg(Stats<T> ob)
{
if(average() == ob.average())
return true;
return false;
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
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>.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
WildCard Argument
 The wildcard simply matches the validity of object.
 The wildcard argument is specified by the ?, and it represents
an unknown type.
boolean same_Avg(Stats<?> ob)
{
if(average() == ob.average())
return true;
return false;
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Generic Method
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Generic Method
 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.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Generic Methods
 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:
static <T, V extends T> boolean isIn (T x, V[] y)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Generic interfaces
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
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.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Generic Interface
interface MinMax<T extends Comparable<T>>
{
T min();
T max();
}
class My<T extends Comparable<T>> implements MinMax<T>
{
…
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Generic constructors
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Generic Constructors
 It is possible for constructors to be generic, even if their class is
not.
Example:
class GenCons {
private double val;
<T extends Number> GenCons(T arg)
{
val = arg.doubleValue();
}
void show_val() { System.out.println("val: " + val); } }
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
ERASURE
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Erasure
 Generic code had to be compatible with pre-existing, non-
generic code.
 Any changes to the syntax of the Java language, or to the
JVM, had to avoid breaking older code.
 Java implements Generics using Erasures to avoid
breaking older codes.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Working of Erasure
 When Java code is compiled, all generic type information
is removed (erased).
 This includes replacing type parameters with their bound
type, which is Object if no explicit bound is specified.
 Then applying the appropriate casts (as determined by the
type arguments) to maintain type compatibility with the
types specified by the type arguments.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Erasures
 The compiler enforces type compatibility.
 It means that no type parameters exist at run time.
 They are simply a source-code mechanism.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Generic restrictions
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Generic Restrictions
1. Type Parameters Can’t Be Instantiated:
It is not possible to create an instance of a type parameter.
Example:
class Gen<T> {
T ob;
Gen() {
ob = new T(); // Illegal
}
}
Because T does not exist at run time, how would the compiler
know what type of object to create?
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Generic Restrictions
2. Restrictions on Static Members :
No static member can use a type parameter declared by the enclosing
class.
Example:
class Wrong<T> {
static T ob;
static T getob() { return ob; }
static void showob() { System.out.println(ob);
} }
Note: We can declare static generic methods, which define their own type
parameters
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Generic Restrictions
3. Generic Array Restrictions:
 We cannot instantiate an array whose base type is a type
parameter.
 We cannot create an array of type-specific generic references.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class Gen<T extends Number> {
T ob;
T vals[]; // OK
Gen(T o, T[] nums) {
ob = o; // This statement is illegal.
// vals = new T[10]; // can't create an array of T
vals = nums; // OK to assign reference to existent array
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
class GenArrays {
public static void main(String args[]) {
Integer n[] = { 1, 2, 3, 4, 5 };
Gen<Integer> iOb = new Gen<Integer>(50, n);
// Can't create an array of type-specific generic references.
// Gen<Integer> gens[] = new Gen<Integer>[10]; // Wrong!
// This is OK.
Gen<?> gens[] = new Gen<?>[10]; // OK
}
}
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Generic Restrictions
4. Generic Exception Restrictions:
 A generic class cannot extend Throwable.
 This means that we cannot create generic exception classes.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Generics

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Interface
InterfaceInterface
Interface
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Java collections
Java collectionsJava collections
Java collections
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
Delegates and events in C#
Delegates and events in C#Delegates and events in C#
Delegates and events in C#
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Method overriding
Method overridingMethod overriding
Method overriding
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 

Andere mochten auch (20)

Interfaces en Java
Interfaces en JavaInterfaces en Java
Interfaces en Java
 
POO - 17 - Interfaces
POO - 17 - InterfacesPOO - 17 - Interfaces
POO - 17 - Interfaces
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Poo Java
Poo JavaPoo Java
Poo Java
 
Java Generics
Java GenericsJava Generics
Java Generics
 
¿Qué es una interface en java?
¿Qué es una interface en java?¿Qué es una interface en java?
¿Qué es una interface en java?
 
Interfaces en java
Interfaces en javaInterfaces en java
Interfaces en java
 
Interfaces en Java
Interfaces en JavaInterfaces en Java
Interfaces en Java
 
Clases abstractas e interfaces en java
Clases abstractas e interfaces en javaClases abstractas e interfaces en java
Clases abstractas e interfaces en java
 
Clases abstractas e interfaces
Clases abstractas e interfacesClases abstractas e interfaces
Clases abstractas e interfaces
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
List classes
List classesList classes
List classes
 
Questions for Class I & II
Questions for Class I & IIQuestions for Class I & II
Questions for Class I & II
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Swing api
Swing apiSwing api
Swing api
 
Packages
PackagesPackages
Packages
 
Jun 2012(1)
Jun 2012(1)Jun 2012(1)
Jun 2012(1)
 
Jdbc
JdbcJdbc
Jdbc
 
Servlets
ServletsServlets
Servlets
 
Event handling
Event handlingEvent handling
Event handling
 

Ähnlich wie Generics

String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)Ravi Kant Sahu
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)Ravi_Kant_Sahu
 
Methods and constructors
Methods and constructorsMethods and constructors
Methods and constructorsRavi_Kant_Sahu
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in JavaRavi_Kant_Sahu
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptmanish kumar
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)Ravi_Kant_Sahu
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)Ravi Kant Sahu
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 

Ähnlich wie Generics (20)

Keywords and classes
Keywords and classesKeywords and classes
Keywords and classes
 
Java keywords
Java keywordsJava keywords
Java keywords
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Array
ArrayArray
Array
 
Java beans
Java beansJava beans
Java beans
 
Inheritance
InheritanceInheritance
Inheritance
 
Methods and constructors
Methods and constructorsMethods and constructors
Methods and constructors
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
 
Overview of Java
Overview of Java Overview of Java
Overview of Java
 
07slide.ppt
07slide.ppt07slide.ppt
07slide.ppt
 
CAP615-Unit1.pptx
CAP615-Unit1.pptxCAP615-Unit1.pptx
CAP615-Unit1.pptx
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Exception handling
Exception handlingException handling
Exception handling
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
Effective Unit Testing
Effective Unit TestingEffective Unit Testing
Effective Unit Testing
 

Mehr von Ravi_Kant_Sahu

Common Programming Errors by Beginners in Java
Common Programming Errors by Beginners in JavaCommon Programming Errors by Beginners in Java
Common Programming Errors by Beginners in JavaRavi_Kant_Sahu
 
Classes and Nested Classes in Java
Classes and Nested Classes in JavaClasses and Nested Classes in Java
Classes and Nested Classes in JavaRavi_Kant_Sahu
 
Genesis and Overview of Java
Genesis and Overview of Java Genesis and Overview of Java
Genesis and Overview of Java Ravi_Kant_Sahu
 
L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variablesRavi_Kant_Sahu
 

Mehr von Ravi_Kant_Sahu (9)

Common Programming Errors by Beginners in Java
Common Programming Errors by Beginners in JavaCommon Programming Errors by Beginners in Java
Common Programming Errors by Beginners in Java
 
Gui programming (awt)
Gui programming (awt)Gui programming (awt)
Gui programming (awt)
 
Event handling
Event handlingEvent handling
Event handling
 
Basic IO
Basic IOBasic IO
Basic IO
 
Packages
PackagesPackages
Packages
 
Classes and Nested Classes in Java
Classes and Nested Classes in JavaClasses and Nested Classes in Java
Classes and Nested Classes in Java
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Genesis and Overview of Java
Genesis and Overview of Java Genesis and Overview of Java
Genesis and Overview of Java
 
L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variables
 

Kürzlich hochgeladen

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 

Kürzlich hochgeladen (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 

Generics

  • 1. Advanced Java Programming Topic: Generics By Ravi Kant Sahu Asst. Professor, LPU
  • 2. Contents  Introduction  Benefits of Generics  Generic Classes and Interfaces  Generic Methods  Wildcard Generic Types  Restrictions on Generics Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 3. Introduction  Enables to create classes, interfaces, and methods in which the type of data upon which they operate is specified as a parameter.  Introduced in Java by jdk 1.5.  Generics means parameterized types.  Generics add the type-safety.  Generics add stability to your code by making more of your bugs detectable at compile time. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 4. Why Generics?  The functionality of Gen class can be achieved without generics by specifying Object type and using proper casting whenever required. Then why we use Generics?  Java compiler does not have knowledge about the type of data actually stored in NonGen. So-  Explicit casts must be employed to retrieve the stored data.  Several type mismatch errors cannot be found until run time. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 5. Why Generics?  Stronger type checks at compile time  Elimination of casts List list = new ArrayList(); list.add("hello"); String s = (String) list.get(0);  Using generics: List<String> list = new ArrayList<String>(); list.add("hello"); String s = list.get(0); // no cast  Enabling programmers to implement generic algorithms. We can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 6. Advantage of Generics  The ability to create type-safe code in which type- mismatch errors are caught at compile time is a key advantage of generics. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 7. 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()); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 8. 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 = new Gen<String>("Generics Test"); strOb.showType(); String str = strOb.getob(); System.out.println("value: " + str); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 9. 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);  The above declaration is an error.  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! Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 10. Generic class Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 11. 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); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 12. 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; }  } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 13. class SimpGen { public static void main(String args[]) { TwoGen<Integer, String> t = new TwoGen<Integer, String>(16920, "Ravi Kant"); t.showTypes(); int v = t.getob1(); System.out.println("value: " + v); String str = t.getob2(); System.out.println("value: " + str); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 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. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 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; } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 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. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 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> Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 18. WILD CARD GeneRICS Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 19. 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. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 20. 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 same_Avg(Stats<T> ob) { if(average() == ob.average()) return true; return false; } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 21. 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>. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 22. WildCard Argument  The wildcard simply matches the validity of object.  The wildcard argument is specified by the ?, and it represents an unknown type. boolean same_Avg(Stats<?> ob) { if(average() == ob.average()) return true; return false; } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 23. Generic Method Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 24. Generic Method  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. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 25. Generic Methods  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: static <T, V extends T> boolean isIn (T x, V[] y) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 26. Generic interfaces Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 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. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 28. Generic Interface interface MinMax<T extends Comparable<T>> { T min(); T max(); } class My<T extends Comparable<T>> implements MinMax<T> { … } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 29. Generic constructors Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 30. Generic Constructors  It is possible for constructors to be generic, even if their class is not. Example: class GenCons { private double val; <T extends Number> GenCons(T arg) { val = arg.doubleValue(); } void show_val() { System.out.println("val: " + val); } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 31. ERASURE Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 32. Erasure  Generic code had to be compatible with pre-existing, non- generic code.  Any changes to the syntax of the Java language, or to the JVM, had to avoid breaking older code.  Java implements Generics using Erasures to avoid breaking older codes. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 33. Working of Erasure  When Java code is compiled, all generic type information is removed (erased).  This includes replacing type parameters with their bound type, which is Object if no explicit bound is specified.  Then applying the appropriate casts (as determined by the type arguments) to maintain type compatibility with the types specified by the type arguments. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 34. Erasures  The compiler enforces type compatibility.  It means that no type parameters exist at run time.  They are simply a source-code mechanism. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 35. Generic restrictions Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 36. Generic Restrictions 1. Type Parameters Can’t Be Instantiated: It is not possible to create an instance of a type parameter. Example: class Gen<T> { T ob; Gen() { ob = new T(); // Illegal } } Because T does not exist at run time, how would the compiler know what type of object to create? Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 37. Generic Restrictions 2. Restrictions on Static Members : No static member can use a type parameter declared by the enclosing class. Example: class Wrong<T> { static T ob; static T getob() { return ob; } static void showob() { System.out.println(ob); } } Note: We can declare static generic methods, which define their own type parameters Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 38. Generic Restrictions 3. Generic Array Restrictions:  We cannot instantiate an array whose base type is a type parameter.  We cannot create an array of type-specific generic references. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 39. class Gen<T extends Number> { T ob; T vals[]; // OK Gen(T o, T[] nums) { ob = o; // This statement is illegal. // vals = new T[10]; // can't create an array of T vals = nums; // OK to assign reference to existent array } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 40. class GenArrays { public static void main(String args[]) { Integer n[] = { 1, 2, 3, 4, 5 }; Gen<Integer> iOb = new Gen<Integer>(50, n); // Can't create an array of type-specific generic references. // Gen<Integer> gens[] = new Gen<Integer>[10]; // Wrong! // This is OK. Gen<?> gens[] = new Gen<?>[10]; // OK } } Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 41. Generic Restrictions 4. Generic Exception Restrictions:  A generic class cannot extend Throwable.  This means that we cannot create generic exception classes. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)