SlideShare ist ein Scribd-Unternehmen logo
1 von 24
Generics
Michael Heron
Introduction
 There is a common technique available in
Java (versions 1.5 and above) and .net
(version 2 and above).
 The Generic Datatype
 Overloading and polymorphism go a long
way towards making an object oriented
system work ‘properly’
 But they only take you to the bridge.
The Problem
 Let’s say we want to create a basic data
structure.
 One that works for any object.
 It’s something straight forward – a queue,
for example.
 How do we do that?
 Well, in older versions of a language we’d
declare the data type as an Object.
The Queue
 Public class Queue {
ArrayList<Object> myObjects;
void addToQueue (Object ob) {
myObjects.add (ob);
}
void removeFromQueue () {
Object ob = myObjects.get(0);
myObjects.remove (0);
return ob;
}
}
The Problem
 We can use casting to turn whatever is on the
queue into whatever class we need:
Person p =
(Person)queue.removeFromQueue();
 This is bad OO.
 It’s not type safe
 We need to enforce discipline to make sure
that we don’t put the wrong things on the
wrong queues.
 The compiler should be doing as much of that
as is feasible.
The Solution
 Both C# and Java offer the Generic as a
solution.
 A class which acts as a type-safe template.
 The syntax is a little awkward, but it allows
us to define the type that should be
associated with a data structure.
 Like we do with ArrayLists.
Queue – Java Generic
import java.util.*;
public class Queue<T> {
ArrayList<T> myList;
public Queue() {
myList = new ArrayList<T>();
}
public void addToQueue(T ob) {
myList.add(ob);
}
public T getFromQueue() {
T ob = myList.get(0);
myList.remove(0);
return ob;
}
public boolean hasMoreElements() {
return (myList.size() != 0);
}
}
Queue – Java Generic
public static void main(String args[]) {
Queue<String> myQueue =
new Queue<String>();
myQueue.addToQueue("Hello!");
myQueue.addToQueue("World!");
while (myQueue.hasMoreElements()) {
System.out.println(myQueue.getFromQue
ue());
}
}
Queue – C# Generic
class Queue<T>
{
ArrayList myObjects;
public Queue ()
{
myObjects = new ArrayList();
}
public void addToStack<T>(T ob)
{
myObjects.Add(ob);
}
public T removeFromStack()
{
T ob = (T)myObjects[0];
myObjects.RemoveAt(0);
return ob;
}
}
}
Why Use Generics?
 Type safe – we can ensure type
incompatibilities are dealt with at the
earliest possible opportunity.
 Simplifies syntax – no need to cast
individual objects.
 Allows for effective deployment of certain
kinds of design patterns.
 Avoids the need for excessive
specialisation of classes.
How do they work?
 It is important to know the different ways
in which variables are bound during the
running of an application.
 Traditionally variables are bound to a
specific context in one of two ways.
 Static binding, which is done at compile
time.
 Dynamic binding, which is done at runtime.
Static Binding
 Explicitly indicating the type of a
parameter allows for the compiler to link
objects and variables when compiled.
 They’re not going to change in that
respect.
 The performance of this is high, and
compile-time checking can be rigorous in
a way that’s not possible otherwise.
Late Binding
 Late binding is used extensively in Java
and C#.
 One key area in which it is used is in
polymorphism.
 When you use Polymorphism, Java adopts
a late binding approach so that it can
properly adapt to the object at runtime.
 It knows the most specialised method to use
when invoked, but only when the object is
bound.
Strongly Typed Languages
 In strongly typed languages, early binding is
the norm.
 We can tell what the context is going to be by
analysing the runtime
 However, late binding needs to be dealt with
either through polymorphism or compile time
casting.
 Generics allow for you to defer the binding of
a data type until its point of usage arrives.
 The <T> parameter is unbound.
 When we instantiate the class, we bind it to a
specific context.
Boxing and Unboxing
 In both Java and C# a related
mechanism is known as autoboxing.
 This is the process of converting a value
variable into an object reference, or vice
versa.
 When a value reference is boxed, it is
stored on the ‘managed heap’.
 A chunk of memory set aside and tended
by the garbage collector.
Wrapper Classes
 Each primitive data type in Java and C#
comes with a corresponding wrapper
class.
 A class designed to provide a way of
dealing with it as a reference.
 It used to be impossible to have an
ArrayList of ints in Java.
 You needed to make them Integer objects
first.
Wrapper Classes
 Autoboxing then is the process at play
when a primitive data type is
encapsulated within a wrapper.
 And vice versa, when it is unwrapped into
its primitive form.
 Autoboxing is a relatively expensive
process.
 If you were doing this a lot, it would be
worth assessing your specific data
manipulation requirements.
Generics and Constraints
 All of this leads to an obvious problem.
 What if we don’t want everything to be on
the table for a generic?
 Luckily, generics allow us to set constraints
on them.
 Limitations that restrict what can be a valid
specification of our class.
 There are six types of these in .NET.
Constraints
Constraint Description
Where T: struct The type argument must be a value type.
Where T: class The type argument must be a reference
type.
Where T: new() The type argument must have a public,
parameterless constructor
Where T: <class name> The type argument must extend from the
indicated class name.
Where T: <interface
name>
The type argument must implement the
specified interface, or be the interface itself
Where T: U The type argument for T must be or derive
from the argument supplied for U.
Example
class Queue<T> where T : IComparable
{
ArrayList myObjects;
public Queue ()
{
myObjects = new ArrayList();
}
public void addToStack<T>(T ob)
{
myObjects.Add(ob);
}
public T removeFromStack()
{
T ob = (T)myObjects[0];
myObjects.RemoveAt(0);
return ob;
}
public Boolean isInQueue(T ob)
{
T ob2;
for (int i = 0; i < myObjects.Count; i++) {
ob2 = (T)myObjects[i];
if (ob2.CompareTo(ob) != -1) {
return true;
}
}
return false;
}
}
Constraints
 Multiple constraints can be applied to the
same parameter.
 And in turn, they can be generic in and of
themselves.
 If you are going to be performing
operations on a type that are not defined
in Object itself, you need to apply a
constraint.
 That will allow for the method to be made
available in a type-safe way.
Multiple Parameters
 Some classes may provide two types.
 For example, Hashtables
 T and U are used conventionally to refer
to parameter 1 and parameter 2.
 You can apply separate constraints to
each of these:
 Where U : class
Where T : iComperable
Unconstrained Types
 With unconstrained types, we have the
following restrictions:
 We cannot use simple logical comparators
on them, because there is no guarantee
the concrete type will support them.
 They will need to be formally cast.
 You can compare to null, but this will
always return false if the type argument is a
value type.
Conclusion
 Generics offer a new and powerful way
to deal with type-safe collections.
 And other kinds of classes.
 Constraints allow us to ensure that we can
access useful methods as required.
 Polymorphism will ensure that we can
reliably access whatever internals we
require.
 They’re available in both C# and Java.

Weitere ähnliche Inhalte

Was ist angesagt?

Chapter 1 Presentation
Chapter 1 PresentationChapter 1 Presentation
Chapter 1 Presentationguest0d6229
 
What is String in Java?
What is String in Java?What is String in Java?
What is String in Java?RAKESH P
 
Covariance, contravariance 觀念分享
Covariance, contravariance 觀念分享Covariance, contravariance 觀念分享
Covariance, contravariance 觀念分享LearningTech
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxingGeetha Manohar
 
Basics of dictionary object
Basics of dictionary objectBasics of dictionary object
Basics of dictionary objectNilanjan Saha
 
Farhaan Ahmed, BCA 2nd Year
Farhaan Ahmed, BCA 2nd YearFarhaan Ahmed, BCA 2nd Year
Farhaan Ahmed, BCA 2nd Yeardezyneecole
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4thConnex
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects newlykado0dles
 
java object oriented presentation
java object oriented presentationjava object oriented presentation
java object oriented presentationAli Ahsan Mujahid
 
String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 
Chapter2 array of objects
Chapter2 array of objectsChapter2 array of objects
Chapter2 array of objectsMahmoud Alfarra
 
Joshua bloch effect java chapter 3
Joshua bloch effect java   chapter 3Joshua bloch effect java   chapter 3
Joshua bloch effect java chapter 3Kamal Mukkamala
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)Anwar Hasan Shuvo
 

Was ist angesagt? (20)

Chapter 1 Presentation
Chapter 1 PresentationChapter 1 Presentation
Chapter 1 Presentation
 
What is String in Java?
What is String in Java?What is String in Java?
What is String in Java?
 
Covariance, contravariance 觀念分享
Covariance, contravariance 觀念分享Covariance, contravariance 觀念分享
Covariance, contravariance 觀念分享
 
Autoboxing and unboxing
Autoboxing and unboxingAutoboxing and unboxing
Autoboxing and unboxing
 
Basics of dictionary object
Basics of dictionary objectBasics of dictionary object
Basics of dictionary object
 
Java String
Java String Java String
Java String
 
Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Farhaan Ahmed, BCA 2nd Year
Farhaan Ahmed, BCA 2nd YearFarhaan Ahmed, BCA 2nd Year
Farhaan Ahmed, BCA 2nd Year
 
Dynamic databinding
Dynamic databindingDynamic databinding
Dynamic databinding
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
강의자료8
강의자료8강의자료8
강의자료8
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects new
 
java object oriented presentation
java object oriented presentationjava object oriented presentation
java object oriented presentation
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Chapter2 array of objects
Chapter2 array of objectsChapter2 array of objects
Chapter2 array of objects
 
Joshua bloch effect java chapter 3
Joshua bloch effect java   chapter 3Joshua bloch effect java   chapter 3
Joshua bloch effect java chapter 3
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
 
Java best practices
Java best practicesJava best practices
Java best practices
 

Ähnlich wie Learn How Generics Provide Type Safety in Java and C# Collections

New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)rashmita_mishra
 
C questions
C questionsC questions
C questionsparm112
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESNikunj Parekh
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshowilias ahmed
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3Naga Muruga
 
Files to submitProperQueue.javaCreate this file and implement .docx
Files to submitProperQueue.javaCreate this file and implement .docxFiles to submitProperQueue.javaCreate this file and implement .docx
Files to submitProperQueue.javaCreate this file and implement .docxmydrynan
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfkarymadelaneyrenne19
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaGlenn Guden
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & AnswersRatnala Charan kumar
 
Collections and generic class
Collections and generic classCollections and generic class
Collections and generic classifis
 
ptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdf
ptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdfptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdf
ptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdfjorgeulises3
 

Ähnlich wie Learn How Generics Provide Type Safety in Java and C# Collections (20)

New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 
C questions
C questionsC questions
C questions
 
JAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICESJAVA CONCEPTS AND PRACTICES
JAVA CONCEPTS AND PRACTICES
 
Jist of Java
Jist of JavaJist of Java
Jist of Java
 
Advance oops concepts
Advance oops conceptsAdvance oops concepts
Advance oops concepts
 
C++ Interview Questions
C++ Interview QuestionsC++ Interview Questions
C++ Interview Questions
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
Lec2
Lec2Lec2
Lec2
 
Files to submitProperQueue.javaCreate this file and implement .docx
Files to submitProperQueue.javaCreate this file and implement .docxFiles to submitProperQueue.javaCreate this file and implement .docx
Files to submitProperQueue.javaCreate this file and implement .docx
 
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdfAbstract Data Types (a) Explain briefly what is meant by the ter.pdf
Abstract Data Types (a) Explain briefly what is meant by the ter.pdf
 
Java mcq
Java mcqJava mcq
Java mcq
 
Object Oriented Programming Concepts using Java
Object Oriented Programming Concepts using JavaObject Oriented Programming Concepts using Java
Object Oriented Programming Concepts using Java
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
 
11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf
 
Collections and generic class
Collections and generic classCollections and generic class
Collections and generic class
 
Collections
CollectionsCollections
Collections
 
ptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdf
ptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdfptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdf
ptu3-harvey-m-deitel-paul-j-deitel-tem-r-nieto-contributor-paul-j-deitel.pdf
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Creating classes and applications in java
Creating classes and applications in javaCreating classes and applications in java
Creating classes and applications in java
 

Mehr von Michael Heron

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMichael Heron
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconductMichael Heron
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkMichael Heron
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility SupportMichael Heron
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and AutershipMichael Heron
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interactionMichael Heron
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityMichael Heron
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - TexturesMichael Heron
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)Michael Heron
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)Michael Heron
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationMichael Heron
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsMichael Heron
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsMichael Heron
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationMichael Heron
 

Mehr von Michael Heron (20)

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility Support
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical Representation
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 

Kürzlich hochgeladen

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 

Kürzlich hochgeladen (20)

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 

Learn How Generics Provide Type Safety in Java and C# Collections

  • 2. Introduction  There is a common technique available in Java (versions 1.5 and above) and .net (version 2 and above).  The Generic Datatype  Overloading and polymorphism go a long way towards making an object oriented system work ‘properly’  But they only take you to the bridge.
  • 3. The Problem  Let’s say we want to create a basic data structure.  One that works for any object.  It’s something straight forward – a queue, for example.  How do we do that?  Well, in older versions of a language we’d declare the data type as an Object.
  • 4. The Queue  Public class Queue { ArrayList<Object> myObjects; void addToQueue (Object ob) { myObjects.add (ob); } void removeFromQueue () { Object ob = myObjects.get(0); myObjects.remove (0); return ob; } }
  • 5. The Problem  We can use casting to turn whatever is on the queue into whatever class we need: Person p = (Person)queue.removeFromQueue();  This is bad OO.  It’s not type safe  We need to enforce discipline to make sure that we don’t put the wrong things on the wrong queues.  The compiler should be doing as much of that as is feasible.
  • 6. The Solution  Both C# and Java offer the Generic as a solution.  A class which acts as a type-safe template.  The syntax is a little awkward, but it allows us to define the type that should be associated with a data structure.  Like we do with ArrayLists.
  • 7. Queue – Java Generic import java.util.*; public class Queue<T> { ArrayList<T> myList; public Queue() { myList = new ArrayList<T>(); } public void addToQueue(T ob) { myList.add(ob); } public T getFromQueue() { T ob = myList.get(0); myList.remove(0); return ob; } public boolean hasMoreElements() { return (myList.size() != 0); } }
  • 8. Queue – Java Generic public static void main(String args[]) { Queue<String> myQueue = new Queue<String>(); myQueue.addToQueue("Hello!"); myQueue.addToQueue("World!"); while (myQueue.hasMoreElements()) { System.out.println(myQueue.getFromQue ue()); } }
  • 9. Queue – C# Generic class Queue<T> { ArrayList myObjects; public Queue () { myObjects = new ArrayList(); } public void addToStack<T>(T ob) { myObjects.Add(ob); } public T removeFromStack() { T ob = (T)myObjects[0]; myObjects.RemoveAt(0); return ob; } } }
  • 10. Why Use Generics?  Type safe – we can ensure type incompatibilities are dealt with at the earliest possible opportunity.  Simplifies syntax – no need to cast individual objects.  Allows for effective deployment of certain kinds of design patterns.  Avoids the need for excessive specialisation of classes.
  • 11. How do they work?  It is important to know the different ways in which variables are bound during the running of an application.  Traditionally variables are bound to a specific context in one of two ways.  Static binding, which is done at compile time.  Dynamic binding, which is done at runtime.
  • 12. Static Binding  Explicitly indicating the type of a parameter allows for the compiler to link objects and variables when compiled.  They’re not going to change in that respect.  The performance of this is high, and compile-time checking can be rigorous in a way that’s not possible otherwise.
  • 13. Late Binding  Late binding is used extensively in Java and C#.  One key area in which it is used is in polymorphism.  When you use Polymorphism, Java adopts a late binding approach so that it can properly adapt to the object at runtime.  It knows the most specialised method to use when invoked, but only when the object is bound.
  • 14. Strongly Typed Languages  In strongly typed languages, early binding is the norm.  We can tell what the context is going to be by analysing the runtime  However, late binding needs to be dealt with either through polymorphism or compile time casting.  Generics allow for you to defer the binding of a data type until its point of usage arrives.  The <T> parameter is unbound.  When we instantiate the class, we bind it to a specific context.
  • 15. Boxing and Unboxing  In both Java and C# a related mechanism is known as autoboxing.  This is the process of converting a value variable into an object reference, or vice versa.  When a value reference is boxed, it is stored on the ‘managed heap’.  A chunk of memory set aside and tended by the garbage collector.
  • 16. Wrapper Classes  Each primitive data type in Java and C# comes with a corresponding wrapper class.  A class designed to provide a way of dealing with it as a reference.  It used to be impossible to have an ArrayList of ints in Java.  You needed to make them Integer objects first.
  • 17. Wrapper Classes  Autoboxing then is the process at play when a primitive data type is encapsulated within a wrapper.  And vice versa, when it is unwrapped into its primitive form.  Autoboxing is a relatively expensive process.  If you were doing this a lot, it would be worth assessing your specific data manipulation requirements.
  • 18. Generics and Constraints  All of this leads to an obvious problem.  What if we don’t want everything to be on the table for a generic?  Luckily, generics allow us to set constraints on them.  Limitations that restrict what can be a valid specification of our class.  There are six types of these in .NET.
  • 19. Constraints Constraint Description Where T: struct The type argument must be a value type. Where T: class The type argument must be a reference type. Where T: new() The type argument must have a public, parameterless constructor Where T: <class name> The type argument must extend from the indicated class name. Where T: <interface name> The type argument must implement the specified interface, or be the interface itself Where T: U The type argument for T must be or derive from the argument supplied for U.
  • 20. Example class Queue<T> where T : IComparable { ArrayList myObjects; public Queue () { myObjects = new ArrayList(); } public void addToStack<T>(T ob) { myObjects.Add(ob); } public T removeFromStack() { T ob = (T)myObjects[0]; myObjects.RemoveAt(0); return ob; } public Boolean isInQueue(T ob) { T ob2; for (int i = 0; i < myObjects.Count; i++) { ob2 = (T)myObjects[i]; if (ob2.CompareTo(ob) != -1) { return true; } } return false; } }
  • 21. Constraints  Multiple constraints can be applied to the same parameter.  And in turn, they can be generic in and of themselves.  If you are going to be performing operations on a type that are not defined in Object itself, you need to apply a constraint.  That will allow for the method to be made available in a type-safe way.
  • 22. Multiple Parameters  Some classes may provide two types.  For example, Hashtables  T and U are used conventionally to refer to parameter 1 and parameter 2.  You can apply separate constraints to each of these:  Where U : class Where T : iComperable
  • 23. Unconstrained Types  With unconstrained types, we have the following restrictions:  We cannot use simple logical comparators on them, because there is no guarantee the concrete type will support them.  They will need to be formally cast.  You can compare to null, but this will always return false if the type argument is a value type.
  • 24. Conclusion  Generics offer a new and powerful way to deal with type-safe collections.  And other kinds of classes.  Constraints allow us to ensure that we can access useful methods as required.  Polymorphism will ensure that we can reliably access whatever internals we require.  They’re available in both C# and Java.