GENERIC TYPES AND THE JAVA COLLECTIONS FRAMEWORK Lecture 15 CS2110 – Fall 2013.

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
Collections CS3250. Sources  Slides by Professor Chuck Allison  Core Java, by Cay S. Horstmann and Gary Cornell  The Java Tutorial 
5-May-15 ArrayLists. 2 ArrayList s and arrays A ArrayList is like an array of Object s Differences between arrays and ArrayList s: Arrays have special.
GENERICS AND THE JAVA COLLECTIONS FRAMEWORK Lecture 15 CS2110 – Spring 2015.
GENERICS AND THE JAVA COLLECTIONS FRAMEWORK Lecture 13 CS2110 – Spring 2014.
11-Jun-15 Generics. A generic is a method that is recompiled with different types as the need arises The bad news: Instead of saying: List words = new.
Java Collections Framework COMP53 Oct 24, Collections Framework A unified architecture for representing and manipulating collections Allows collections.
15-Jun-15 Lists in Java Part of the Collections Framework.
Java Collections. Lecture Objectives To understand the concepts of Java collections To be able to implement Java programs based on Collections.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
Lists in Java Part of the Collections Framework. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection.
Java Review Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
12-Jul-15 Lists in Java Part of the Collections Framework.
The Collections Framework A Brief Introduction. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector.
15-Jul-15 Generics. ArrayList s and arrays A ArrayList is like an array of Object s, but... Arrays use [ ] syntax; ArrayList s use object syntax An ArrayList.
Java's Collection Framework
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
CS2110: SW Development Methods Textbook readings: MSD, Chapter 8 (Sect. 8.1 and 8.2) But we won’t implement our own, so study the section on Java’s Map.
Data Structures and Abstract Data Types "Get your data structures correct first, and the rest of the program will write itself." - David Jones.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
(c) University of Washington14-1 CSC 143 Java Collections.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Effective Java: Generics Last Updated: Spring 2009.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
1 Java: AP Curriculum Focus and Java Subset Alyce Brady.
Data Design and Implementation. Definitions of Java TYPES Atomic or primitive type A data type whose elements are single, non-decomposable data items.
Chapter 18 Java Collections Framework
1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Generics and Collections Course Lecture Slides 19 th July 2010 “Never.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
1 Collections Framework A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain:
Lecture 4 Generic programming Advanced Java Programming 1 dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
GENERICS AND THE JAVA COLLECTIONS FRAMEWORK Lecture 16 CS2110 – Fall 2015 Photo credit: Andrew Kennedy.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
4-Mar-16 Introduction to Collections. Revision questions True false questions 0 for False 1 for True Please do not answer anything other than the above.
Collections Dwight Deugo Nesa Matic
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
JAVA GENERICS Lecture 16 CS2110 – Spring 2016 Photo credit: Andrew Kennedy.
 2016, Marcus Biel, ArrayList Marcus Biel, Software Craftsman
Using the Java Collection Libraries COMP 103 # T2
Introduction to Collections
Introduction to Collections
Introduction to Collections
Introduction to Collections
Generics 27-Nov-18.
Generic Types and the Java Collections Framework
Introduction to Collections
ArrayLists 22-Feb-19.
Collections Framework
Introduction to Collections
MINI-MAX using trees and the Java Collections Framework
Generics 2-May-19.
Part of the Collections Framework
Presentation transcript:

GENERIC TYPES AND THE JAVA COLLECTIONS FRAMEWORK Lecture 15 CS2110 – Fall 2013

Textbook and Homework  Generics: Appendix B  Generic types we discussed: Chapters 1-3, 15  Homework: Use Google to find out about the old Java Vector collection type. Vector has been “deprecated”, meaning that it is no longer recommended and being phased out. What more modern type has taken over Vector ’s old roles? 2

Generic Types in Java 3  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 4 //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 static int cCount(Collection c) { int cnt = 0; Iterator i = c.iterator(); while (i.hasNext()) { cnt += ((String)i.next()).length(); return cnt; } old new

Example – nicer looking loop 5 //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 6 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 grades = new HashMap (); 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

Type Casting 7  In effect, Java inserts the correct cast automatically, based on the declared type (“Type inference”).  In this example, grades.get("John") is automatically known to have static type Integer Map grades = new HashMap (); 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();

An Aside: Autoboxing 8  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 grades = new HashMap (); 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 grades = new HashMap (); grades.put("John", 67); grades.put("Jane", 88); grades.put("Fred", 72); sum = sum + grades.get("John");

Using Generic Types 9  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

Advantage of Generics 10  Declaring Collection c tells us something about the variable c (i.e., c holds only Strings)  This is true wherever c is used  The compiler checks this and won’t compile code that violates this  Without use of generic types, explicit casting must be used  A cast tells us something the programmer thinks is true at a single point in the code  The Java virtual machine checks whether the programmer is right only at runtime

Subtypes: Example 11 Stack s = new Stack (); s.push(new Integer(7)); Stack t = s; // Gives compiler error t.push("bad idea"); System.out.println(s.pop().intValue()); Stack is not a subtype of Stack Stack s = new Stack (); s.push(new Integer(7)); Stack t = s; // Compiler allows this t.push("bad idea");// Produces a warning System.out.println(s.pop().intValue()); //Runtime error! However, Stack is a subtype of Stack (for backward compatibility with previous Java versions)

Programming with Generic Interface Types 12  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(); }

Wildcard Type Parameters  When modifying old non-generic Java code into modern generic code, developers encountered all sorts of problems  People were using the type inheritance hierarchy very actively and some styles of coding didn’t map nicely to generics.  Wildcards were added as a very flexible way to extend generics enough to over those cases  We don’t really need them in cs2110, but it is good to know how this notation looks and how it works 13

Wildcards: Simplest case 14 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” 15  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 Integer s in our List  Wildcards let us specify that the objects must implement this interface without “over constraining” the argument type static void sort (List c) {... }

Fancy wildcard cases  You can actually create complicated expressions using wildcards  E.g. objects that all implement the Comparable and the List interfaces and that extend ZooAnimal  Very rare that people building a Java project need to use these features today unless they are building new utilities to add to JUtil  … but within the Java compiler and the JUtil library they are surprisingly common. 16

Generic Classes 17 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 18 public class InsertionSort > { 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; }

The Generic argument can be used more than once in a method 19  Adding all elements of an array to a Collection  See the online Java Tutorial for more information on generic types and generic methods static void a2c(Object[] a, Collection c) { for (Object o : a) { c.add(o); // compile time error } public class myClass {... static void a2c(T[] a, Collection c) { for (T o : a) { c.add(o); // better, and correct } good bad

Java Collections Framework 20  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

JCF Interfaces and Classes  Interfaces  Collection  Set (no duplicates)  SortedSet  List (duplicates OK)  Map (i.e., Dictionary)  SortedMap  Iterator  Iterable  ListIterator  Classes  HashSet  TreeSet  ArrayList  LinkedList  HashMap  TreeMap 21

java.util.Collection (an interface) 22  public int size();  Return number of elements in collection  public boolean isEmpty();  Return true iff collection holds no elements  public boolean add(E x);  Make sure the collection includes x; returns true if collection has changed (some collections allow duplicates, some don’t)  public boolean contains(Object x);  Returns true iff collection contains x (uses equals( ) method)  public boolean remove(Object x);  Removes a single instance of x from the collection; returns true if collection has changed  public Iterator iterator();  Returns an Iterator that steps through elements of collection

Iterators: How “foreach” works  The notation for(Something var: collection) { … } is really a form of shorthand  It compiles into this “old code”:  The two ways of doing this are identical but the foreach loop is nicer looking.  You can create your own iterable collections 23 Iterator _i = collection.iterator(); while (_i.hasNext()) { Something var = _i.Next();... Your code... }

java.util.Iterator (an interface) 24  public boolean hasNext();  Returns true if the iteration has more elements  public E next();  Returns the next element in the iteration  Throws NoSuchElementException if no next element  public void remove();  The element most recently returned by next() is removed from the underlying collection  Throws IllegalStateException if next() not yet called or if remove() already called since last next()  Throws UnsupportedOperationException if remove() not supported

Additional Methods of Collection 25  public Object[] toArray()  Returns a new array containing all the elements of this collection  public T[] toArray(T[] dest)  Returns an array containing all the elements of this collection; uses dest as that array if it can  Bulk Operations:  public boolean containsAll(Collection c);  public boolean addAll(Collection c);  public boolean removeAll(Collection c);  public boolean retainAll(Collection c);  public void clear();

java.util.Set (an interface) 26  Set extends Collection  Set inherits all its methods from Collection  A Set contains no duplicates  If you attempt to add() an element twice then the second add() will return false (i.e., the Set has not changed)  Write a method that checks if a given word is within a Set of words  Write a method that removes all words longer than 5 letters from a Set  Write methods for the union and intersection of two Set s

Set Implementations 27  java.util.HashSet (a hashtable)  Constructors public HashSet(); public HashSet(Collection c); public HashSet(int initialCapacity); public HashSet(int initialCapacity, float loadFactor);  java.util.TreeSet (a balanced BST [red-black tree])  Constructors public TreeSet(); public TreeSet(Collection c);...

java.util.SortedSet (an interface) 28  SortedSet extends Set  For a SortedSet, the iterator() returns the elements in sorted order  Methods (in addition to those inherited from Set ):  public E first(); Returns the first (lowest) object in this set  public E last(); Returns the last (highest) object in this set  public Comparator comparator(); Returns the Comparator being used by this sorted set if there is one; returns null if the natural order is being used  …

java.lang.Comparable (an interface) 29  public int compareTo(T x);  Returns a value ( 0) (< 0) implies this is before x (= 0) implies this.equals(x) is true (> 0) implies this is after x  Many classes implement Comparable  String, Double, Integer, Char, java.util.Date,…  If a class implements Comparable then that is considered to be the class’s natural ordering

java.util.Comparator (an interface) 30  public int compare(T x1, T x2);  Returns a value ( 0) (< 0) implies x1 is before x2 (= 0) implies x1.equals(x2) is true (> 0) implies x1 is after x2  Can often use a Comparator when a class’s natural order is not the one you want  String.CASE_INSENSITIVE_ORDER is a predefined Comparator  java.util.Collections.reverseOrder() returns a Comparator that reverses the natural order

SortedSet Implementations 31  java.util.TreeSet  constructors: public TreeSet(); public TreeSet(Collection c); public TreeSet(Comparator comparator);...  Write a method that prints out a SortedSet of words in order  Write a method that prints out a Set of words in order

java.util.List (an interface) 32  List extends Collection  Items in a list can be accessed via their index (position in list)  The add() method always puts an item at the end of the list  The iterator() returns the elements in list-order  Methods (in addition to those inherited from Collection ):  public E get(int index); Returns the item at position index in the list  public E set(int index, E x); Places x at position index, replacing previous item; returns the previous item  public void add(int index, E x); Places x at position index, shifting items to make room  public E remove(int index); Remove item at position index, shifting items to fill the space; Returns the removed item  public int indexOf(Object x); Return the index of the first item in the list that equals x (x.equals())  …

List Implementations  java.util.ArrayList (an array; doubles the length each time room is needed)  Constructors public ArrayList(); public ArrayList(int initialCapacity); public ArrayList(Collection c);  java.util.LinkedList (a doubly-linked list)  Constructors public LinkedList(); public LinkedList(Collection c);  Each includes some additional useful methods specific to its class that the other one lacks 33

Efficiency Depends on Implementation 34  Object x = list.get(k);  O(1) time for ArrayList  O(k) time for LinkedList  list.remove(0);  O(n) time for ArrayList  O(1) time for LinkedList  if (set.contains(x))...  O(1) expected time for HashSet  O(log n) for TreeSet

What if you need O(1) for both?  Database systems have this issue  They often build “secondary index” structures  For example, perhaps the data is in an ArrayList  But they might build a HashMap as a quick way to find desired items  The O(n) lookup becomes an O(1) operation! 35