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

PPT
Jdk1.5 Features
PPTX
Java Generics
PPTX
Generic Programming in java
PPTX
Evolution of c# - by K.Jegan
PPT
Generics in java
PPTX
Effective Java - Chapter 3: Methods Common to All Objects
PPT
Md03 - part3
PPTX
Chapter 2 c#
Jdk1.5 Features
Java Generics
Generic Programming in java
Evolution of c# - by K.Jegan
Generics in java
Effective Java - Chapter 3: Methods Common to All Objects
Md03 - part3
Chapter 2 c#

What's hot (19)

PPTX
Best Coding Practices in Java and C++
PPTX
PPSX
Net framework session01
PPTX
Vb ch 3-object-oriented_fundamentals_in_vb.net
PPT
Of Lambdas and LINQ
PPT
Chapter 9 - Characters and Strings
PPT
M C6java3
PDF
C++ Object oriented concepts & programming
PDF
Language tour of dart
PPTX
OCA Java SE 8 Exam Chapter 2 Operators & Statements
PPTX
Code smells and remedies
PPTX
Comparable/ Comparator
PPTX
LEARN C# PROGRAMMING WITH GMT
PPT
Chapter 8 - Exceptions and Assertions Edit summary
PPT
M C6java7
PPTX
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
PPT
Effective Java - Methods Common to All Objects
PPTX
The Go Programing Language 1
PPTX
Pj01 3-java-variable and data types
Best Coding Practices in Java and C++
Net framework session01
Vb ch 3-object-oriented_fundamentals_in_vb.net
Of Lambdas and LINQ
Chapter 9 - Characters and Strings
M C6java3
C++ Object oriented concepts & programming
Language tour of dart
OCA Java SE 8 Exam Chapter 2 Operators & Statements
Code smells and remedies
Comparable/ Comparator
LEARN C# PROGRAMMING WITH GMT
Chapter 8 - Exceptions and Assertions Edit summary
M C6java7
OCA Java SE 8 Exam Chapter 1 Java Building Blocks
Effective Java - Methods Common to All Objects
The Go Programing Language 1
Pj01 3-java-variable and data types
Ad

Viewers also liked (9)

PPT
Entrees sorties
PPT
9. Input Output in java
PPTX
Understanding java streams
PPT
Java stream
PPTX
Java Input Output (java.io.*)
ODP
IO In Java
PDF
PPT
Java Input Output and File Handling
PDF
Java Course 8: I/O, Files and Streams
Entrees sorties
9. Input Output in java
Understanding java streams
Java stream
Java Input Output (java.io.*)
IO In Java
Java Input Output and File Handling
Java Course 8: I/O, Files and Streams
Ad

Similar to Generics (20)

PPTX
Generics Module 2Generics Module Generics Module 2.pptx
PPT
SOEN6441.generics.ppt
PPT
SOEN6441.genericsSOEN6441.genericsSOEN6441.generics
PPTX
PPT
Generic
PPT
Generics Module 2Generics ModuleGenerics Module 2
PPT
templates.ppt
PPTX
Variable, Functions, Scoping and Variable Conversion
PPTX
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
PPTX
Notes(1).pptx
PPTX
More Little Wonders of C#/.NET
PPTX
Generic Collections and learn how to use it
PPTX
CSharp_03_Generics_introduction_withexamples
PPTX
Typescript: Beginner to Advanced
PPTX
Presentation 4th
PPTX
lec 2.pptx
PPT
Csharp_mahesh
PPTX
21CS642 Module 2 Generics PPT.pptx VI SEM CSE
Generics Module 2Generics Module Generics Module 2.pptx
SOEN6441.generics.ppt
SOEN6441.genericsSOEN6441.genericsSOEN6441.generics
Generic
Generics Module 2Generics ModuleGenerics Module 2
templates.ppt
Variable, Functions, Scoping and Variable Conversion
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Notes(1).pptx
More Little Wonders of C#/.NET
Generic Collections and learn how to use it
CSharp_03_Generics_introduction_withexamples
Typescript: Beginner to Advanced
Presentation 4th
lec 2.pptx
Csharp_mahesh
21CS642 Module 2 Generics PPT.pptx VI SEM CSE

Recently uploaded (20)

PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Approach and Philosophy of On baking technology
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Empathic Computing: Creating Shared Understanding
PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPTX
Big Data Technologies - Introduction.pptx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
1. Introduction to Computer Programming.pptx
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
Tartificialntelligence_presentation.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Unlocking AI with Model Context Protocol (MCP)
Advanced methodologies resolving dimensionality complications for autism neur...
Approach and Philosophy of On baking technology
NewMind AI Weekly Chronicles - August'25-Week II
Diabetes mellitus diagnosis method based random forest with bat algorithm
Empathic Computing: Creating Shared Understanding
Assigned Numbers - 2025 - Bluetooth® Document
Big Data Technologies - Introduction.pptx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
20250228 LYD VKU AI Blended-Learning.pptx
1. Introduction to Computer Programming.pptx
The Rise and Fall of 3GPP – Time for a Sabbatical?
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Dropbox Q2 2025 Financial Results & Investor Presentation
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Tartificialntelligence_presentation.pptx
Encapsulation_ Review paper, used for researhc scholars
Unlocking AI with Model Context Protocol (MCP)

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/