Understanding Generics in Java
1 Introduction
Generics in Java, introduced in Java 5, enable type-safe programming by allowing classes,
interfaces, and methods to operate on objects of various types using type parameters. This
document covers Generic Classes and Methods, Bounded Types, and Wildcards, including
their theory, advantages, disadvantages, use cases, and example programs.
2 Generic Classes and Methods
2.1 Theory
Generics allow classes and methods to work with different data types while ensuring type
safety at compile time. A Generic Class uses a type parameter to handle various types, while
a Generic Method operates similarly within a class or independently.
2.2 Advantages
• Type Safety: Prevents runtime errors like ClassCastException.
• Code Reusability: A single class/method works with multiple types.
• No Casting: Eliminates explicit casting when retrieving objects.
• Readability: Type parameters make code self-explanatory.
2.3 Disadvantages
• Complexity: Can make code harder to read.
• No Primitives: Requires wrapper classes (e.g., Integer instead of int).
• Learning Curve: Challenging for beginners.
2.4 Use Cases
• Collections Framework (e.g., ArrayList<T>, HashMap<K,V>).
• Reusable libraries and custom data structures like stacks or queues.
1
2.5 Where and Why Used
Generics are used for flexibility with type safety, especially in collections and APIs, to avoid
casting and type mismatches.
2.6 Example Program
1 class Box <T > {
2 private T content ;
3 public void setContent ( T content ) {
4 this . content = content ;
5 }
6 public T getContent () {
7 return content ;
8 }
9 }
10
11 class Utility {
12 public static <T > void printItem ( T item ) {
13 System . out . println ( " Item : " + item ) ;
14 }
15 }
16
17 public class GenericDemo {
18 public static void main ( String [] args ) {
19 Box < Integer > intBox = new Box < >() ;
20 intBox . setContent (123) ;
21 System . out . println ( " Integer Box : " + intBox . getContent () )
;
22
23 Box < String > strBox = new Box < >() ;
24 strBox . setContent ( " Hello " ) ;
25 System . out . println ( " String Box : " + strBox . getContent () ) ;
26
27 Utility . printItem (456) ;
28 Utility . printItem ( " World " ) ;
29 }
30 }
Output:
Integer Box: 123
String Box: Hello
Item: 456
Item: World
2
3 Bounded Types
3.1 Theory
Bounded types restrict type parameters to a specific class or interface using extends (upper
bound) or super (lower bound, used in wildcards). For example, T extends Number restricts
T to Number or its subclasses.
3.2 Advantages
• Restricted Flexibility: Ensures specific types are used.
• Access to Methods: Allows calling methods of the bounding type.
• Type Safety: Maintains safety with restricted types.
3.3 Disadvantages
• Limited Flexibility: Less flexible than unbounded generics.
• Complexity: Adds complexity to code.
3.4 Use Cases
• APIs requiring specific type properties (e.g., Number methods).
• Processing objects with common interfaces (e.g., Comparable).
3.5 Where and Why Used
Bounded types are used when specific type hierarchies are needed to access common methods
while maintaining type safety.
3.6 Example Program
1 class NumericBox < T extends Number > {
2 private T content ;
3 public NumericBox ( T content ) {
4 this . content = content ;
5 }
6 public double getDoubleValue () {
7 return content . doubleValue () ;
8 }
9 }
10
11 public class BoundedTypeDemo {
12 public static void main ( String [] args ) {
13 NumericBox < Integer > intBox = new NumericBox < >(100) ;
14 System . out . println ( " Integer Value as Double : " + intBox .
getDoubleValue () ) ;
3
15
16 NumericBox < Double > doubleBox = new NumericBox < >(99.99) ;
17 System . out . println ( " Double Value : " + doubleBox .
getDoubleValue () ) ;
18 }
19 }
Output:
Integer Value as Double: 100.0
Double Value: 99.99
4 Wildcards
4.1 Theory
Wildcards (?) provide flexibility in generics when the exact type is unknown. Types include:
• Unbounded Wildcard (?): Accepts any type.
• Upper-Bounded (? extends Type): Accepts Type or subclasses.
• Lower-Bounded (? super Type): Accepts Type or superclasses.
4.2 Advantages
• Flexibility: Accepts a range of types.
• Readability: Expressive for generic operations.
• Safe Operations: Upper bounds for reading, lower bounds for writing.
4.3 Disadvantages
• Restrictions: Upper bounds prevent adding, lower bounds limit reading.
• Complexity: Harder to understand for beginners.
4.4 Use Cases
• Upper-bounded: Reading from collections (e.g., List<? extends Number>).
• Lower-bounded: Writing to collections (e.g., List<? super Integer>).
• Unbounded: Generic operations like checking size.
4.5 Where and Why Used
Wildcards are used in method parameters for flexibility, especially in collections, to handle
various types safely.
4
4.6 Example Program
1 import java . util . ArrayList ;
2 import java . util . List ;
3
4 public class WildcardDemo {
5 public static double sumList ( List <? extends Number > list ) {
6 double sum = 0.0;
7 for ( Number num : list ) {
8 sum += num . doubleValue () ;
9 }
10 return sum ;
11 }
12
13 public static void addNumbers ( List <? super Integer > list ) {
14 list . add (10) ;
15 list . add (20) ;
16 }
17
18 public static void main ( String [] args ) {
19 List < Integer > intList = new ArrayList < >() ;
20 intList . add (1) ;
21 intList . add (2) ;
22 System . out . println ( " Sum of Integer List : " + sumList (
intList ) ) ;
23
24 List < Double > doubleList = new ArrayList < >() ;
25 doubleList . add (1.5) ;
26 doubleList . add (2.5) ;
27 System . out . println ( " Sum of Double List : " + sumList (
doubleList ) ) ;
28
29 List < Number > numList = new ArrayList < >() ;
30 addNumbers ( numList ) ;
31 System . out . println ( " Number List after adding : " + numList
);
32
33 List <? > anyList = new ArrayList < String >() ;
34 System . out . println ( " Size of any list : " + anyList . size () )
;
35 }
36 }
Output:
Sum of Integer List: 3.0
Sum of Double List: 4.0
Number List after adding: [10, 20]
Size of any list: 0
5
5 Summary
Concept Purpose Advantages DisadvantagesUse Case
Generic Classes/Methods Work with Type safety, Complexity, Collections,
multiple reusability, no no primitives custom data
types safely casting structures
Bounded Types Restrict types Access spe- Less flexibil- APIs needing
to a class/in- cific meth- ity, complex- specific type
terface ods, type ity properties
safety
Wildcards Flexible Flexibility, Restrictions Collections
method safe read- on read- processing,
parameters /write opera- /write, generic APIs
tions complexity
6 Conclusion
Generics provide type safety and flexibility in Java, widely used in the Collections Framework
and custom APIs. Bounded types restrict generics to specific hierarchies, while wildcards en-
hance method parameter flexibility. The provided examples demonstrate practical applications,
ensuring type safety and code reusability.