The concept of generics in java collections framework and how it provides a way to communicate the type of elements in a collection to the compiler. It also covers the use of wildcards and autoboxing in collections. Examples and advantages of using generics in java.
Download Java Collections Framework: Understanding Generics and Wildcards in Collections and more Slides Object Oriented Programming in PDF only on Docsity!
Generic Types and the
Java Collections Framework
Generic Types in Java
When using a collection (e.g.,
LinkedList, HashSet, HashMap),
we generally have a single type T of
elements that we store in it (e.g.,
Integer, String)
Before Java 5, when extracting an
element, had to cast it to T before we
could invoke T's methods
Compiler could not check that the cast
was correct at compile-time, since it
didn't know what T was
Inconvenient and unsafe, could fail at
runtime
Generics in Java provide a way to communicate T, the type of elements in a collection, to the compiler
Compiler can check that you have
used the collection consistently
Result: safer and more-efficient
code
Example – nicer looking loop
//Count the number of characters in the strings in //a collection of strings. static int cCount(Collection c) { int cnt = 0; Iterator i = c.iterator(); while (i.hasNext()) cnt += ((String)i.next()).length(); return cnt; } // Count the number of characters in //a collection of strings. static int cCount(Collection c) { int cnt = 0; for(String s: c) cnt += s.length(); return cnt; } old new
Another Example
Map grades = new HashMap(); grades.put("John", new Integer(67)); grades.put("Jane", new Integer(88)); grades.put("Fred", new Integer(72)); Integer x = (Integer)grades.get("John"); sum = sum + x.intValue(); Map<String, Integer> grades = new HashMap<String, Integer>(); grades.put("John", new Integer(67)); grades.put("Jane", new Integer(88)); grades.put("Fred", new Integer(72)); Integer x = grades.get("John"); sum = sum + x.intValue(); old new
An Aside: Autoboxing
Java also has autoboxing and auto-unboxing of primitive types, so the example can be simplified
AutoBoxing/Unboxing: converts from “int” to “Integer”, “byte” to “Byte”, etc Map<String,Integer> grades = new HashMap<String,Integer>(); grades.put("John",new Integer(67)); grades.put("Jane",new Integer(88)); grades.put("Fred",new Integer(72)); Integer x = grades.get("John"); sum = sum + x.intValue()); Map<String,Integer> grades = new HashMap<String,Integer>(); grades.put("John", 67); grades.put("Jane", 88); grades.put("Fred", 72); sum = sum + grades.get("John");
Using Generic Types
is read, “of T”
For example: Stack is read, “Stack of Integer”. Here the “T”
is “Integer”.
The type annotation informs the compiler that all extractions from this collection should be automatically cast to T Specify type in declaration, can be checked at compile time
Can eliminate explicit casts
Subtypes: Example
Stack s = new Stack(); s.push(new Integer(7)); Stack
Programming with Generic Interface Types
To use the interface List, supply an actual type argument, e.g., List
All occurrences of the formal type parameter (E in this case) are replaced by the actual type argument (Integer in this case) public interface List { // E is a type variable void add(E x); Iterator iterator(); } public interface Iterator { E next(); boolean hasNext(); void remove(); }
Wildcards: Simplest case
void printCollection(Collection c) { Iterator i = c.iterator(); while (i.hasNext()) { System.out.println(i.next()); } } void printCollection(Collection c) { for (Object e : c) { System.out.println(e); } } old Wildcard void printCollection(Collection<?> c) { for (Object e : c) { System.out.println(e); } } bad A collection of some single type of objects. We don’t care what that type is, but this whoever created the collection is required to have specified the type
Wildcards are usually “bounded”
• Note that if we declared the parameter c to be of type
List then we could not sort an object of type
List (even though String is a subtype of Comparable)
Suppose Java treated List and List as a subtype of List
Then, for instance, a method passed an object of type List would be able to store Integers in our List
• Wildcards let us specify that the objects must implement this
interface without “over constraining” the argument type
static void sort (List<? extends Comparable> c) { ... }
Generic Classes
public class Queue extends AbstractBag { private java.util.LinkedList queue = new java.util.LinkedList(); public void insert(T item) { queue.add(item); } public T extract() throws java.util.NoSuchElementException { return queue.remove(); } public void clear() { queue.clear(); } public int size() { return queue.size(); } }
Generic Classes
public class InsertionSort<T extends Comparable> { public void sort(T[] x) { for (int i = 1; i < x.length; i++) { // invariant is: x[0],...,x[i-1] are sorted // now find rightful position for x[i] T tmp = x[i]; int j; for (j = i; j > 0 && x[j-1].compareTo(tmp) > 0; j--) x[j] = x[j-1]; x[j] = tmp; } } }
Java Collections Framework
Collections: holders that let you store and organize objects in useful ways for efficient access The package java.util includes interfaces and classes for a general collection framework Goal: conciseness A few concepts that are broadly useful Not an exhaustive set of useful concepts The collections framework provides Interfaces (i.e., ADTs) Implementations