SlideShare a Scribd company logo
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/

More Related Content

What's hot

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
 
Generics C#
Generics C#Generics C#
Net framework session01
Net framework session01Net framework session01
Net framework session01
Vivek 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.net
bantamlak dejene
 
Of Lambdas and LINQ
Of Lambdas and LINQOf Lambdas and LINQ
Of Lambdas and LINQ
BlackRabbitCoder
 
Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
Eduardo Bergavera
 
M C6java3
M C6java3M C6java3
M C6java3
mbruggen
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
nirajmandaliya
 
Language tour of dart
Language tour of dartLanguage tour of dart
Language tour of dart
Imran 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
 
Code smells and remedies
Code smells and remediesCode smells and remedies
Code smells and remedies
Md.Mojibul Hoque
 
Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ Comparator
Sean McElrath
 
LEARN C# PROGRAMMING WITH GMT
LEARN C# PROGRAMMING WITH GMTLEARN C# PROGRAMMING WITH GMT
LEARN C# PROGRAMMING WITH GMT
Tabassum Ghulame Mustafa
 
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
Eduardo Bergavera
 
M C6java7
M C6java7M C6java7
M C6java7
mbruggen
 
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 Objects
Roshan 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 types
SasidharaRaoMarrapu
 

What's hot (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
 

Viewers also liked

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 java
Nilesh Dalvi
 
Understanding java streams
Understanding java streamsUnderstanding java streams
Understanding java streams
Shahjahan Samoon
 
Java stream
Java streamJava stream
Java stream
Arati Gadgil
 
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 Java
parag
 
Java I/O
Java I/OJava 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
Sunil 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 Streams
Anton Keks
 

Viewers also liked (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
 

Similar to Generics

Generics
GenericsGenerics
Generics in dot net
Generics in dot netGenerics in dot net
Generics Module 2Generics Module Generics Module 2.pptx
Generics Module 2Generics Module Generics Module 2.pptxGenerics Module 2Generics Module Generics Module 2.pptx
Generics Module 2Generics Module Generics Module 2.pptx
AlvasCSE
 
SOEN6441.genericsSOEN6441.genericsSOEN6441.generics
SOEN6441.genericsSOEN6441.genericsSOEN6441.genericsSOEN6441.genericsSOEN6441.genericsSOEN6441.generics
SOEN6441.genericsSOEN6441.genericsSOEN6441.generics
tahircs1
 
SOEN6441.generics.ppt
SOEN6441.generics.pptSOEN6441.generics.ppt
SOEN6441.generics.ppt
ElieMambou1
 
Java
JavaJava
Generic
GenericGeneric
Generic
abhay singh
 
templates.ppt
templates.ppttemplates.ppt
templates.ppt
Saiganesh124618
 
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
Marco Parenzan
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
InfinityWorld3
 
More Little Wonders of C#/.NET
More Little Wonders of C#/.NETMore Little Wonders of C#/.NET
More Little Wonders of C#/.NET
BlackRabbitCoder
 
Typescript: Beginner to Advanced
Typescript: Beginner to AdvancedTypescript: Beginner to Advanced
Typescript: Beginner to Advanced
Talentica Software
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
Connex
 
lec 2.pptx
lec 2.pptxlec 2.pptx
lec 2.pptx
AhsanAli64749
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
Ananthu Mahesh
 
Md06 advance class features
Md06 advance class featuresMd06 advance class features
Md06 advance class features
Rakesh Madugula
 
Java
JavaJava
CSharp for Unity Day 3
CSharp for Unity Day 3CSharp for Unity Day 3
CSharp for Unity Day 3
Duong Thanh
 
Intake 38 2
Intake 38 2Intake 38 2
Intake 38 2
Mahmoud Ouf
 
C_plus_plus
C_plus_plusC_plus_plus
C_plus_plus
Ralph Weber
 

Similar to Generics (20)

Generics
GenericsGenerics
Generics
 
Generics in dot net
Generics in dot netGenerics in dot net
Generics in dot net
 
Generics Module 2Generics Module Generics Module 2.pptx
Generics Module 2Generics Module Generics Module 2.pptxGenerics Module 2Generics Module Generics Module 2.pptx
Generics Module 2Generics Module Generics Module 2.pptx
 
SOEN6441.genericsSOEN6441.genericsSOEN6441.generics
SOEN6441.genericsSOEN6441.genericsSOEN6441.genericsSOEN6441.genericsSOEN6441.genericsSOEN6441.generics
SOEN6441.genericsSOEN6441.genericsSOEN6441.generics
 
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
 

Recently uploaded

Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
Mariano Tinti
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 

Recently uploaded (20)

Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 

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/