SlideShare ist ein Scribd-Unternehmen logo
1 von 28
GENERICS IN JAVA
Shahjahan Samoon
What are Generics?
• In any nontrivial software project, bugs are simply a fact of life.
• Careful planning, programming, and testing can help reduce their pervasiveness, but
somehow, somewhere, they'll always find a way to creep into your code.
• This becomes especially apparent as new features are introduced and your code base
grows in size and complexity.
What are Generics?
• Fortunately, some bugs are easier to detect than others.
Compile-time bugs, for example, can be detected early on; you
can use the compiler's error messages to figure out what the
problem is and fix it, right then and there.
• Runtime bugs, however, can be much more problematic; they
don't always surface immediately.
• Generics add stability to your code by making more of your bugs
detectable at compile time.
What are Generics?
• In a nutshell, generics enable types (classes and interfaces) to be parameters when
defining classes, interfaces and methods.
• Much like the more familiar formal parameters used in method declarations, type
parameters provide a way for you to re-use the same code with different inputs.
• The difference is that the inputs to formal parameters are values, while the inputs to
type parameters are types.
Why Generics?
1. Elimination of casts.
The following code snippet without generics requires
casting:
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);
When re-written to use generics, the code does not
require casting:
List<String> list = new ArrayList<String>();

list.add("hello");
String s = list.get(0); // no cast
Why Generics?
2. Enabling programmers to implement generic algorithms.
By using generics, programmers can implement generic algorithms that
work on collections of different types, can be customized, and are type
safe and easier to read.
3. Stronger type checks at compile time.
A Java compiler applies strong type checking to generic code and issues
errors if the code violates type safety. Fixing compile-time errors is easier
than fixing runtime errors, which can be difficult to find.
Generic Types:
• A generic type is a generic class or interface that is parameterized over
types.
• The following Box class will be modified to demonstrate the concept.
public class Box {
private Object object;

}

public void set(Object object){
this.object = object;
}
public Object get() {
return object;
}
Generic Types:
• Since its methods accept or return an Object,
• you are free to pass in whatever you want, provided that it is not one of
the primitive types.
• There is no way to verify, at compile time, how the class is used.
• One part of the code may place an Integer in the box and expect to get
Integers out of it, while another part of the code may mistakenly pass in
a String, resulting in a runtime error.
Generic Types:
• A generic class is defined with the following format:
• class name<T1, T2, ..., Tn> { /* ... */ }
• The type parameter section, delimited by angle brackets (<>), follows the
class name. It specifies the type parameters (also called type variables)
T1, T2, ..., and Tn.
A Generic Version of the Box Class
To update the Box class to use generics, you create a generic type declaration by changing the code
"public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used
anywhere inside the class.

With this change, the Box class becomes:
public class Box<T> {
private T t;

}

public void set(T t) {
this.t = t;
}
public T get() {
return t;
}
A Generic Version of the Box Class

• All occurrences of Object are replaced by T.
• A type variable can be any non-primitive type you specify:
 class type
 interface type
 array type
Type Parameter Naming Conventions
• By convention, type parameter names are single, uppercase letters.
The most commonly used type parameter names are:
E - Element (used extensively by the Java Collections Framework)
K - Key
N - Number
T - Type
V - Value
Invoking and Instantiating a Generic Type
• To reference the generic Box class from within your code, you must
perform a generic type invocation, which replaces T with some concrete
value, such as Integer:
Box<Integer> integerBox;

• It simply declares that integerBox will hold a reference to a "Box of
Integer", which is how Box<Integer> is read.
• You can think of a generic type invocation as being similar to an ordinary
method invocation, but instead of passing an argument to a method, you
are passing a type argument — Integer in this case — to the Box class
itself.
Invoking and Instantiating a Generic Type
• To instantiate this class, use the new keyword, as usual, but place
<Integer> between the class name and the parenthesis:

Box<Integer> integerBox = new Box<Integer>();

Box<Integer> integerBox = new Box<>();
Type Parameter and Type Argument:
• Many developers use the terms "type parameter" and "type
argument" interchangeably, but these terms are not the same.
When coding, one provides type arguments in order to create a
parameterized type. Therefore, the T in Box<T> is a type
parameter and the String in Box<Integer> is a type argument. This
lesson observes this definition when using these terms.
Multiple Type Parameters
• As mentioned previously, a generic class can have multiple type
parameters. For example, the generic OrderedPair class, which
implements the generic Pair interface:

public interface Pair<K, V> {
public K getKey();
public V getValue();
}
public class OrderedPair<K, V> implements Pair<K, V> {
private K key;
private V value;
public OrderedPair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}

public V getValue() {
return value;
}
}
Multiple Type Parameters
The following statements create two instantiations of the OrderedPair class:
Pair<String, Integer> p1 = new OrderedPair<String, Integer>("Even", 8);
Pair<String, String> p2 = new OrderedPair<String, String>("hello", "world");
The code, new OrderedPair<String, Integer>, instantiates K as a String and V as an
Integer. Therefore, the parameter types of OrderedPair's constructor are String and
Integer, respectively. Due to autoboxing, is it valid to pass a String and an int to the class.
You can also substitute a type parameter (i.e., K or V) with a parameterized type (i.e.,
Box<Integer>). For example, using the OrderedPair<K, V> example:
OrderedPair<String, Box<Integer>> p = new OrderedPair<>(“numbers", new Box<Integer>());
Raw Types
• A raw type is the name of a generic class or interface without any type
arguments.
• To create a parameterized type of Box<T>, you supply an actual type
argument for the formal type parameter T:
Box<Integer> intBox = new Box<>();

• If the actual type argument is omitted, you create a raw type of Box<T>:
Box rawBox = new Box();

• Therefore, Box is the raw type of the generic type Box<T>. However, a
non-generic class or interface type is not a raw type.
Raw Types
• Raw types show up in legacy code because lots of API classes (such
as the Collections classes) were not generic prior to JDK 5.0.
• When using raw types, you essentially get pre-generics behavior —
a Box gives you Objects. For backward compatibility, assigning a
parameterized type to its raw type is allowed:
Box<String> stringBox = new Box<>();
Box rawBox = stringBox;

// OK
Raw Types
• But if you assign a raw type to a parameterized type, you get a
warning:
Box rawBox = new Box();
Box<Integer> intBox = rawBox;

// rawBox is a raw type of Box<T>
// warning: unchecked conversion

• You also get a warning if you use a raw type to invoke generic methods
defined in the corresponding generic type:
Box<String> stringBox = new Box<>();
Box rawBox = stringBox;
rawBox.set(8); // warning: unchecked invocation to set(T)

• The warning shows that raw types bypass generic type checks,
deferring the catch of unsafe code to runtime. Therefore, you should
avoid using raw types.
Unchecked Error Messages
• As mentioned previously, when mixing legacy code with generic
code, you may encounter warning messages similar to the
following:
Note: Example.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Generic Methods
• Generic methods are methods that introduce their own type
parameters.
• This is similar to declaring a generic type, but the type
parameter's scope is limited to the method where it is declared.
• Static and non-static generic methods are allowed, as well as
generic class constructors.
Generic Methods
• The syntax for a generic method includes a type parameter, inside
angle brackets, and appears before the method's return type. For
static generic methods, the type parameter section must appear
before the method's return type.
public static <T> void print(T t){
return t;

}
Bounded Type Parameters
• There may be times when you want to restrict the types that can
be used as type arguments in a parameterized type.
• For example, a method that operates on numbers might only want
to accept instances of Number or its subclasses. This is what
bounded type parameters are for.
• To declare a bounded type parameter, list the type parameter's
name, followed by the extends keyword, followed by its upper
bound, which in this example is Number.
• Note that, in this context, extends is used in a general sense to mean
either "extends" (as in classes) or "implements" (as in interfaces).
Bounded Type Parameters
public <T extends Number> void inspect(T t){
System.out.println(“Type: " + t.getClass().getName());
}
Bounded Type Parameters
• In addition to limiting the types you can use to instantiate a generic type,
bounded type parameters allow you to invoke methods defined in the bounds:
public class NaturalNumber<T extends Integer> {
private T n;
public NaturalNumber(T n) { this.n = n; }
public boolean isEven() {
return n.intValue() % 2 == 0;
}

}

• The isEven method invokes the intValue method defined in the Integer class
through n.
Refferences & Further Readings
• http://docs.oracle.com/javase/tutorial/java/generics/

Weitere ähnliche Inhalte

Was ist angesagt?

Best Coding Practices in Java and C++
Best Coding Practices in Java and C++Best Coding Practices in Java and C++
Best Coding Practices in Java and C++Nitin Aggarwal
 
Net framework session01
Net framework session01Net framework session01
Net framework session01Vivek chan
 
Vb ch 3-object-oriented_fundamentals_in_vb.net
Vb ch 3-object-oriented_fundamentals_in_vb.netVb ch 3-object-oriented_fundamentals_in_vb.net
Vb ch 3-object-oriented_fundamentals_in_vb.netbantamlak dejene
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and StringsEduardo Bergavera
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programmingnirajmandaliya
 
Language tour of dart
Language tour of dartLanguage tour of dart
Language tour of dartImran Qasim
 
OCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & StatementsOCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & Statementsİbrahim Kürce
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ ComparatorSean McElrath
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summaryEduardo Bergavera
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocksİbrahim Kürce
 
Effective Java - Methods Common to All Objects
Effective Java - Methods Common to All ObjectsEffective Java - Methods Common to All Objects
Effective Java - Methods Common to All ObjectsRoshan Deniyage
 
The Go Programing Language 1
The Go Programing Language 1The Go Programing Language 1
The Go Programing Language 1İbrahim Kürce
 
Pj01 3-java-variable and data types
Pj01 3-java-variable and data typesPj01 3-java-variable and data types
Pj01 3-java-variable and data typesSasidharaRaoMarrapu
 

Was ist angesagt? (19)

Best Coding Practices in Java and C++
Best Coding Practices in Java and C++Best Coding Practices in Java and C++
Best Coding Practices in Java and C++
 
Generics C#
Generics C#Generics C#
Generics C#
 
Net framework session01
Net framework session01Net framework session01
Net framework session01
 
Vb ch 3-object-oriented_fundamentals_in_vb.net
Vb ch 3-object-oriented_fundamentals_in_vb.netVb ch 3-object-oriented_fundamentals_in_vb.net
Vb ch 3-object-oriented_fundamentals_in_vb.net
 
Of Lambdas and LINQ
Of Lambdas and LINQOf Lambdas and LINQ
Of Lambdas and LINQ
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
 
M C6java3
M C6java3M C6java3
M C6java3
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
 
Language tour of dart
Language tour of dartLanguage tour of dart
Language tour of dart
 
OCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & StatementsOCA Java SE 8 Exam Chapter 2 Operators & Statements
OCA Java SE 8 Exam Chapter 2 Operators & Statements
 
Code smells and remedies
Code smells and remediesCode smells and remedies
Code smells and remedies
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ Comparator
 
LEARN C# PROGRAMMING WITH GMT
LEARN C# PROGRAMMING WITH GMTLEARN C# PROGRAMMING WITH GMT
LEARN C# PROGRAMMING WITH GMT
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
 
M C6java7
M C6java7M C6java7
M C6java7
 
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building BlocksOCA Java SE 8 Exam Chapter 1 Java Building Blocks
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
 
Effective Java - Methods Common to All Objects
Effective Java - Methods Common to All ObjectsEffective Java - Methods Common to All Objects
Effective Java - Methods Common to All Objects
 
The Go Programing Language 1
The Go Programing Language 1The Go Programing Language 1
The Go Programing Language 1
 
Pj01 3-java-variable and data types
Pj01 3-java-variable and data typesPj01 3-java-variable and data types
Pj01 3-java-variable and data types
 

Andere mochten auch

Entrees sorties
Entrees sortiesEntrees sorties
Entrees sortiesyazidds2
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in javaNilesh Dalvi
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streamsShahjahan Samoon
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)Om Ganesh
 
IO In Java
IO In JavaIO In Java
IO In Javaparag
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File HandlingSunil OS
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsAnton Keks
 

Andere mochten auch (9)

Entrees sorties
Entrees sortiesEntrees sorties
Entrees sorties
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
 
Java stream
Java streamJava stream
Java stream
 
Java Input Output (java.io.*)
Java Input Output (java.io.*)Java Input Output (java.io.*)
Java Input Output (java.io.*)
 
IO In Java
IO In JavaIO In Java
IO In Java
 
Java I/O
Java I/OJava I/O
Java I/O
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 

Ähnlich wie Generics (20)

Generics
GenericsGenerics
Generics
 
Generics in dot net
Generics in dot netGenerics in dot net
Generics in dot net
 
SOEN6441.generics.ppt
SOEN6441.generics.pptSOEN6441.generics.ppt
SOEN6441.generics.ppt
 
Java
JavaJava
Java
 
Generic
GenericGeneric
Generic
 
templates.ppt
templates.ppttemplates.ppt
templates.ppt
 
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptxStatic abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
More Little Wonders of C#/.NET
More Little Wonders of C#/.NETMore Little Wonders of C#/.NET
More Little Wonders of C#/.NET
 
Typescript: Beginner to Advanced
Typescript: Beginner to AdvancedTypescript: Beginner to Advanced
Typescript: Beginner to Advanced
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
lec 2.pptx
lec 2.pptxlec 2.pptx
lec 2.pptx
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
 
Md06 advance class features
Md06 advance class featuresMd06 advance class features
Md06 advance class features
 
Java
JavaJava
Java
 
CSharp for Unity Day 3
CSharp for Unity Day 3CSharp for Unity Day 3
CSharp for Unity Day 3
 
Intake 38 2
Intake 38 2Intake 38 2
Intake 38 2
 
C_plus_plus
C_plus_plusC_plus_plus
C_plus_plus
 
Game Programming 04 - Style & Design Principles
Game Programming 04 - Style & Design PrinciplesGame Programming 04 - Style & Design Principles
Game Programming 04 - Style & Design Principles
 
Typescript
TypescriptTypescript
Typescript
 

Kürzlich hochgeladen

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
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
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 

Kürzlich hochgeladen (20)

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
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
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
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
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 

Generics

  • 2. What are Generics? • In any nontrivial software project, bugs are simply a fact of life. • Careful planning, programming, and testing can help reduce their pervasiveness, but somehow, somewhere, they'll always find a way to creep into your code. • This becomes especially apparent as new features are introduced and your code base grows in size and complexity.
  • 3. What are Generics? • Fortunately, some bugs are easier to detect than others. Compile-time bugs, for example, can be detected early on; you can use the compiler's error messages to figure out what the problem is and fix it, right then and there. • Runtime bugs, however, can be much more problematic; they don't always surface immediately. • Generics add stability to your code by making more of your bugs detectable at compile time.
  • 4. What are Generics? • In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. • Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. • The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.
  • 5. Why Generics? 1. Elimination of casts. The following code snippet without generics requires casting: List list = new ArrayList(); list.add("hello"); String s = (String) list.get(0); When re-written to use generics, the code does not require casting: List<String> list = new ArrayList<String>(); list.add("hello"); String s = list.get(0); // no cast
  • 6. Why Generics? 2. Enabling programmers to implement generic algorithms. By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read. 3. Stronger type checks at compile time. A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.
  • 7. Generic Types: • A generic type is a generic class or interface that is parameterized over types. • The following Box class will be modified to demonstrate the concept. public class Box { private Object object; } public void set(Object object){ this.object = object; } public Object get() { return object; }
  • 8. Generic Types: • Since its methods accept or return an Object, • you are free to pass in whatever you want, provided that it is not one of the primitive types. • There is no way to verify, at compile time, how the class is used. • One part of the code may place an Integer in the box and expect to get Integers out of it, while another part of the code may mistakenly pass in a String, resulting in a runtime error.
  • 9. Generic Types: • A generic class is defined with the following format: • class name<T1, T2, ..., Tn> { /* ... */ } • The type parameter section, delimited by angle brackets (<>), follows the class name. It specifies the type parameters (also called type variables) T1, T2, ..., and Tn.
  • 10. A Generic Version of the Box Class To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class. With this change, the Box class becomes: public class Box<T> { private T t; } public void set(T t) { this.t = t; } public T get() { return t; }
  • 11. A Generic Version of the Box Class • All occurrences of Object are replaced by T. • A type variable can be any non-primitive type you specify:  class type  interface type  array type
  • 12. Type Parameter Naming Conventions • By convention, type parameter names are single, uppercase letters. The most commonly used type parameter names are: E - Element (used extensively by the Java Collections Framework) K - Key N - Number T - Type V - Value
  • 13. Invoking and Instantiating a Generic Type • To reference the generic Box class from within your code, you must perform a generic type invocation, which replaces T with some concrete value, such as Integer: Box<Integer> integerBox; • It simply declares that integerBox will hold a reference to a "Box of Integer", which is how Box<Integer> is read. • You can think of a generic type invocation as being similar to an ordinary method invocation, but instead of passing an argument to a method, you are passing a type argument — Integer in this case — to the Box class itself.
  • 14. Invoking and Instantiating a Generic Type • To instantiate this class, use the new keyword, as usual, but place <Integer> between the class name and the parenthesis: Box<Integer> integerBox = new Box<Integer>(); Box<Integer> integerBox = new Box<>();
  • 15. Type Parameter and Type Argument: • Many developers use the terms "type parameter" and "type argument" interchangeably, but these terms are not the same. When coding, one provides type arguments in order to create a parameterized type. Therefore, the T in Box<T> is a type parameter and the String in Box<Integer> is a type argument. This lesson observes this definition when using these terms.
  • 16. Multiple Type Parameters • As mentioned previously, a generic class can have multiple type parameters. For example, the generic OrderedPair class, which implements the generic Pair interface: public interface Pair<K, V> { public K getKey(); public V getValue(); }
  • 17. public class OrderedPair<K, V> implements Pair<K, V> { private K key; private V value; public OrderedPair(K key, V value) { this.key = key; this.value = value; } public K getKey() { return key; } public V getValue() { return value; } }
  • 18. Multiple Type Parameters The following statements create two instantiations of the OrderedPair class: Pair<String, Integer> p1 = new OrderedPair<String, Integer>("Even", 8); Pair<String, String> p2 = new OrderedPair<String, String>("hello", "world"); The code, new OrderedPair<String, Integer>, instantiates K as a String and V as an Integer. Therefore, the parameter types of OrderedPair's constructor are String and Integer, respectively. Due to autoboxing, is it valid to pass a String and an int to the class. You can also substitute a type parameter (i.e., K or V) with a parameterized type (i.e., Box<Integer>). For example, using the OrderedPair<K, V> example: OrderedPair<String, Box<Integer>> p = new OrderedPair<>(“numbers", new Box<Integer>());
  • 19. Raw Types • A raw type is the name of a generic class or interface without any type arguments. • To create a parameterized type of Box<T>, you supply an actual type argument for the formal type parameter T: Box<Integer> intBox = new Box<>(); • If the actual type argument is omitted, you create a raw type of Box<T>: Box rawBox = new Box(); • Therefore, Box is the raw type of the generic type Box<T>. However, a non-generic class or interface type is not a raw type.
  • 20. Raw Types • Raw types show up in legacy code because lots of API classes (such as the Collections classes) were not generic prior to JDK 5.0. • When using raw types, you essentially get pre-generics behavior — a Box gives you Objects. For backward compatibility, assigning a parameterized type to its raw type is allowed: Box<String> stringBox = new Box<>(); Box rawBox = stringBox; // OK
  • 21. Raw Types • But if you assign a raw type to a parameterized type, you get a warning: Box rawBox = new Box(); Box<Integer> intBox = rawBox; // rawBox is a raw type of Box<T> // warning: unchecked conversion • You also get a warning if you use a raw type to invoke generic methods defined in the corresponding generic type: Box<String> stringBox = new Box<>(); Box rawBox = stringBox; rawBox.set(8); // warning: unchecked invocation to set(T) • The warning shows that raw types bypass generic type checks, deferring the catch of unsafe code to runtime. Therefore, you should avoid using raw types.
  • 22. Unchecked Error Messages • As mentioned previously, when mixing legacy code with generic code, you may encounter warning messages similar to the following: Note: Example.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.
  • 23. Generic Methods • Generic methods are methods that introduce their own type parameters. • This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. • Static and non-static generic methods are allowed, as well as generic class constructors.
  • 24. Generic Methods • The syntax for a generic method includes a type parameter, inside angle brackets, and appears before the method's return type. For static generic methods, the type parameter section must appear before the method's return type. public static <T> void print(T t){ return t; }
  • 25. Bounded Type Parameters • There may be times when you want to restrict the types that can be used as type arguments in a parameterized type. • For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for. • To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number. • Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).
  • 26. Bounded Type Parameters public <T extends Number> void inspect(T t){ System.out.println(“Type: " + t.getClass().getName()); }
  • 27. Bounded Type Parameters • In addition to limiting the types you can use to instantiate a generic type, bounded type parameters allow you to invoke methods defined in the bounds: public class NaturalNumber<T extends Integer> { private T n; public NaturalNumber(T n) { this.n = n; } public boolean isEven() { return n.intValue() % 2 == 0; } } • The isEven method invokes the intValue method defined in the Integer class through n.
  • 28. Refferences & Further Readings • http://docs.oracle.com/javase/tutorial/java/generics/