Module 4: Generic Types and
Collections
Reusable and Type-Safe Data Structures in Java
Learning Objectives
• Understand purpose of Generics
• Apply Generic classes/methods
• Explain Wildcards and Subtyping
• Explore Java Collection Interfaces
Introduction to Generics
• Generics enable type-safe, reusable classes
and methods.
• Benefits:
– Compile-time type safety
– No casting required
– Code reusability
• Example:
List<String> names = new ArrayList<>();
Simple Generics
• Example:
• class Box<T>{ T value; void set(T v){value=v;} T
get(){return value;} }
• Usage:
• Box<Integer> intBox=new Box<>();
intBox.set(10);
Generics and Subtyping
• Subtyping of classes != subtyping of generic
types.
• List<Object> ≠ List<String>
• Ensures type safety and prevents runtime
errors.
Wildcards
• Allow flexible subtyping.
• Types:
– ? – unknown type
– ? extends T – upper bound
– ? super T – lower bound
• Example:
• void printList(List<?> list){ for(Object o:list)
System.out.println(o); }
Generic Methods
• Methods with type parameters.
• Example:
• public <T> void display(T item){
System.out.println(item); }
Java Collections Framework (JCF)
• Unified architecture for storing and
manipulating collections.
• Core Interfaces:
• Collection, List, Set, Queue, Map
Set Interface
• Unordered collection of unique elements.
• Example:
• Set<String> s=new HashSet<>(); s.add("A");
s.add("A"); // Duplicate ignored
List Interface
• Ordered collection allowing duplicates.
• Example:
• List<String> names=new ArrayList<>();
names.add("Alice"); names.get(0);
Queue and Deque Interfaces
• Queue = FIFO structure (LinkedList,
PriorityQueue)
• Deque = Double-ended queue (ArrayDeque)
• Example:
• Queue<Integer> q=new LinkedList<>();
q.offer(10); q.poll();
Map Interface
• Key-value pairs with unique keys.
• Example:
• Map<Integer,String> map=new HashMap<>();
map.put(1,"One"); map.get(1);
Object Ordering
• Interfaces:
• Comparable<T> (natural order)
• Comparator<T> (custom order)
• Example:
• class Student implements
Comparable<Student>{public int
compareTo(Student s){return marks-s.marks;}}
SortedSet and SortedMap
• SortedSet maintains sorted order (TreeSet)
• SortedMap maintains keys in order (TreeMap)
• Example:
• SortedSet<Integer> s=new TreeSet<>();
s.add(5); s.add(2);
Summary
• Generics = Type safety + Reusability
• Wildcards add flexibility
• Collections provide rich, standardized data
structures
• Prefer interface references (e.g., List over
ArrayList)