Generic Types in Java. Example. Another Example. Type Casting. An Aside: Autoboxing 4/16/2013 GENERIC TYPES AND THE JAVA COLLECTIONS FRAMEWORK.



Similar documents
Collections in Java. Arrays. Iterators. Collections (also called containers) Has special language support. Iterator (i) Collection (i) Set (i),

Class 32: The Java Collections Framework

Data Structures in the Java API

Practical Session 4 Java Collections

Basic Programming and PC Skills: Basic Programming and PC Skills:

The Java Collections Framework

Principles of Software Construction: Objects, Design and Concurrency. Java Collections. toad Fall 2013

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

JAVA COLLECTIONS FRAMEWORK

CMSC 202H. ArrayList, Multidimensional Arrays

Working with Java Collections

Data Structures and Algorithms

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

Java Collection Framework hierarchy. What is Data Structure? Chapter 20 Lists, Stacks, Queues, and Priority Queues

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

CSE 2123 Collections: Sets and Iterators (Hash functions and Trees) Jeremy Morris

Software Development with UML and Java 2 SDJ I2, Spring 2010

Java Interview Questions and Answers

CS 111 Classes I 1. Software Organization View to this point:

D06 PROGRAMMING with JAVA

AP Computer Science Java Subset

Java Map and Set collections

CompSci-61B, Data Structures Final Exam

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

e ag u g an L g ter lvin v E ram Neal G g ro va P Ja

Crash Course in Java

Chapter 8: Bags and Sets

CmpSci 187: Programming with Data Structures Spring 2015

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Computer Programming I

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Stacks. Data Structures and Data Types. Collections

Computer. Course Description

J a v a Quiz (Unit 3, Test 0 Practice)

Stacks and queues. Algorithms and Data Structures, Fall Rasmus Pagh. Based on slides by Kevin Wayne, Princeton

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Data Structures and Algorithms Lists

Programming with Data Structures

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Contents. 9-1 Copyright (c) N. Afshartous

Big O and Limits Abstract Data Types Data Structure Grand Tour.

Introduction to Programming System Design. CSCI 455x (4 Units)

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Semantic Analysis: Types and Type Checking

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

Java from a C perspective. Plan

Lecture 2: Data Structures Steven Skiena. skiena

Introduction to Object-Oriented Programming

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Chapter 3: Restricted Structures Page 1

1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: Data Structures

Part I. Multiple Choice Questions (2 points each):

Static vs. Dynamic. Lecture 10: Static Semantics Overview 1. Typical Semantic Errors: Java, C++ Typical Tasks of the Semantic Analyzer

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Implementation Aspects of OO-Languages

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Sorting revisited. Build the binary search tree: O(n^2) Traverse the binary tree: O(n) Total: O(n^2) + O(n) = O(n^2)

Moving from CS 61A Scheme to CS 61B Java

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

LINKED DATA STRUCTURES

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Introduction to Data Structures

Android Application Development Course Program

core 2 Basic Java Syntax

COMPUTER SCIENCE. Paper 1 (THEORY)

Stack Allocation. Run-Time Data Structures. Static Structures

CS211 Spring 2005 Final Exam May 17, Solutions. Instructions

Introducing Variance into the Java Programming Language DRAFT

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

Sequential Data Structures

Chapter 5 Names, Bindings, Type Checking, and Scopes

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Introduction to Java

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

To Java SE 8, and Beyond (Plan B)

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

Memory management. Announcements. Safe user input. Function pointers. Uses of function pointers. Function pointer example

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Lecture 11 Doubly Linked Lists & Array of Linked Lists. Doubly Linked Lists

C++FA 3.1 OPTIMIZING C++

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

Java Application Developer Certificate Program Competencies

Pseudo code Tutorial and Exercises Teacher s Version

Transcription:

Generic Types in Java 2 GENERIC TYPES AND THE JAVA COLLECTIONS FRAMEWORK Lecture 15 CS2110 Spring 2013 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 Another Example 3 4 new //removes 4-letter words from c //elements must be Strings static void purge(collection c) { Iterator i = c.iterator(); if (((String)i.next()).length() == 4) i.remove(); //removes 4-letter words from c static void purge(collection<string> c) { Iterator<String> i = c.iterator(); if (i.next().length() == 4) i.remove(); new Map grades = new HashMap(); Integer x = (Integer)grades.get("John"); Map<String, Integer> grades = new HashMap<String, Integer>(); Type Casting An Aside: Autoboxing 5 In effect, Java inserts the correct cast automatically, based on the declared type In this example, grades.get("john") is automatically cast to Integer Map<String, Integer> grades = new HashMap<String, Integer>(); 6 Java also has autoboxing and auto-unboxing of primitive types, so the example can be simplified 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)); sum = sum + x.intvalue()); AutoBoxing/Unboxing: converts from int to Integer, byte to Byte, etc 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"); 1

Using Generic Types Advantage of Generics 7 <T> is read, of T For example: Stack<Integer> is read, Stack of Integer The type annotation <T> 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 8 Declaring Collection<String> c tells us something about the variable c (i.e., c hs 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 Programming with Generic Types 9 10 Stack<Integer> is not a subtype of Stack<Object> Stack<Integer> s = new Stack<Integer>(); s.push(new Integer(7)); Stack<Object> t = s; // Gives compiler error t.push("bad idea"); System.out.println(s.pop().intValue()); However, Stack<Integer> is a subtype of Stack (for backward compatibility with previous Java versions) public interface List<E> { // E is a type variable void add(e x); Iterator<E> iterator(); public interface Iterator<E> { E next(); boolean hasnext(); void remove(); Stack<Integer> s = new Stack<Integer>(); 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! To use the interface List<E>, supply an actual type argument, e.g., List<Integer> All occurrences of the formal type parameter (E in this case) are replaced by the actual type argument (Integer in this case) Wildcards Wildcards are usually bounded 11 12 bad Wildcard void printcollection(collection c) { Iterator i = c.iterator(); System.out.println(i.next()); void printcollection(collection<object> c) { for (Object e : c) { System.out.println(e); void printcollection(collection<?> c) { for (Object e : c) { System.out.println(e); static void sort (List<? extends Comparable> c) {... Note that if we declared the parameter c to be of type List<Comparable> then we could not sort an object of type List<String> (even though String is a subtype of Comparable) Suppose Java treated List<String> and List<Integer> as a subtype of List<Comparable> Then, for instance, a method passed an object of type List<Comparable> would be able to store Integers in our List<String> Wildcards specify exactly what types are allowed 2

Generic Methods Generic Classes 13 Adding all elements of an array to a Collection good bad static void a2c(object[] a, Collection<?> c) { for (Object o : a) { c.add(o); // compile time error public class myclass<t> {... static void a2c(t[] a, Collection<T> c) { for (T o : a) { c.add(o); // ok 14 public class Queue<T> extends AbstractBag<T> { private java.util.linkedlist<t> queue = new java.util.linkedlist<t>(); public void insert(t item) { queue.add(item); public T extract() throws java.util.nosuchelementexception { return queue.remove(); public void clear() { queue.clear(); See the online Java Tutorial for more information on generic types and generic methods public int size() { return queue.size(); Generic Classes Java Collections Framework 15 16 public class InsertionSort<T extends Comparable<T>> { 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; Collections: hers 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 17 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 18 java.util.collection<e> (an interface) public int size(); Return number of elements in collection public boolean isempty(); Return true iff collection hs 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<E> iterator(); Returns an Iterator that steps through elements of collection 3

java.util.iterator<e> (an interface) Additional Methods of Collection<E> 19 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 20 public Object[] toarray() Returns a new array containing all the elements of this collection public <T> T[] toarray(t[] dest) Returns an array containing all the elements of this collection; uses dest as that array if it can 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 Bulk Operations: public boolean containsall(collection<?> c); public boolean addall(collection<? extends E> c); public boolean removeall(collection<?> c); public boolean retainall(collection<?> c); public void clear(); java.util.set<e> (an interface) Set Implementations 21 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 Sets 22 java.util.hashset<e> (a hashtable) Constructors public HashSet(); public HashSet(Collection<? extends E> c); public HashSet(int initialcapacity); public HashSet(int initialcapacity, float loadfactor); java.util.treeset<e> (a balanced BST [red-black tree]) Constructors public TreeSet(); public TreeSet(Collection<? extends E> c);... java.util.sortedset<e> (an interface) java.lang.comparable<t> (an interface) 23 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<? super E> comparator(); Returns the Comparator being used by this sorted set if there is one; returns null if the natural order is being used 24 public int compareto(t x); Returns a value (< 0), (= 0), or (> 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 4

java.util.comparator<t> (an interface) SortedSet Implementations 25 public int compare(t x1, T x2); Returns a value (< 0), (= 0), or (> 0) (< 0) implies x1 is before x2 (= 0) implies x1.equals(x2) is true (> 0) implies x1 is after x2 26 java.util.treeset<e> constructors: public TreeSet(); public TreeSet(Collection<? extends E> c); public TreeSet(Comparator<? super E> comparator);... 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 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<e> (an interface) List Implementations 27 28 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()) java.util.arraylist<e> (an array; doubles the length each time room is needed) Constructors public ArrayList(); public ArrayList(int initialcapacity); public ArrayList(Collection<? extends E> c); java.util.linkedlist <E> (a doubly-linked list) Constructors public LinkedList(); public LinkedList(Collection<? extends E> c); Both include some additional useful methods specific to that class Efficiency Depends on Implementation 29 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 5