Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani. The Collection Framework

Similar documents
Software 1 with Java. Java Collections Framework. Collection Interfaces. Online Resources. The Collection Interface

Software 1 with Java. Recitation No. 6 (Collections)

תוכנה 1 מבני נתונים גנריים

CS2110: Software Development Methods. Maps and Sets in Java

COMP 250. Lecture 29. interfaces. Nov. 18, 2016

Collections. James Brucker

17. Java Collections. Organizing Data. Generic List in Java: java.util.list. Type Parameters ( Parameteric Polymorphism ) Data Structures that we know

תוכנה 1 מבני נתונים גנריים

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, ,

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures

Topic 10: The Java Collections Framework (and Iterators)

CMSC 202H. Containers and Iterators

Java Collections Framework

Adam Blank Lecture 5 Winter 2019 CS 2. Introduction to Programming Methods

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

Collections, Maps and Generics

CS2110: Software Development Methods. Maps and Sets in Java

Computer Science II (Spring )

SUMMARY INTRODUCTION COLLECTIONS FRAMEWORK. Introduction Collections and iterators Linked list Array list Hash set Tree set Maps Collections framework

Overview of Java ArrayList, HashTable, HashMap, Hashet,LinkedList

Abstract data types (again) Announcements. Example ADT an integer bag (next) The Java Collections Framework

CIS 265 Exam 2 First Name Last Name

//instance variables //methods. Foo x = new Foo(); Interface: also a type of objects public interface Bar {

What is an Iterator? An iterator is an abstract data type that allows us to iterate through the elements of a collection one by one

An Interface with Generics

CSE 143. Computer Programming II

Introduction to Computer Science I

Algorithms. Produced by. Eamonn de Leastar

CS108, Stanford Handout #8. Java Generics

CSE 143 Lecture 14. Interfaces; Abstract Data Types (ADTs) reading: 9.5, 11.1; 16.4

Set<Integer> s = new TreeSet<Integer>(); s.add( 7 ); s.add( 7 ); System.out.println( s.size() );

CS11 Java. Winter Lecture 8

CONTAİNERS COLLECTİONS

Generics Collection Framework

Java Magistère BFA

USAL1J: Java Collections. S. Rosmorduc

DM550 Introduction to Programming part 2. Jan Baumbach.

Collections class Comparable and Comparator. Slides by Mark Hancock (adapted from notes by Craig Schock)

Lecture 15 Summary. Collections Framework. Collections class Comparable and Comparator. Iterable, Collections List, Set Map

Adam Blank Lecture 9 Autumn 2016 CSE 143. Computer Programming II

Beside List, there are two other common collections. Set: like a mathematical set, unordered, no repetitions.

Object-Oriented Programming with Java

COMP 250. Lecture 32. interfaces. (Comparable, Iterable & Iterator) Nov. 22/23, 2017

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Family Name:... Other Names:... ID Number:... Signature... Model Solutions. COMP 103: Test 1. 9th August, 2013

DM550 Introduction to Programming part 2. Jan Baumbach.

Programmieren II. Collections. Alexander Fraser. May 28, (Based on material from T. Bögel)

AP CS Unit 7: Interfaces. Programs

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss

CMPSCI 187: Programming With Data Structures. Lecture #21: Array-Based Lists David Mix Barrington 26 October 2012

ABSTRACT DATA TYPES: COLLECTIONS, LISTS, SETS, MAP, QUEUES. Thursday, June 30, 2011

First Name Last Name ID#

EXAMINATIONS 2016 TRIMESTER 2

CSE 143X. Accelerated Computer Programming I/II

5 More sophisticated behavior

27/04/2012. Objectives. Collection. Collections Framework. "Collection" Interface. Collection algorithm. Legacy collection

Today's Agenda. > To give a practical introduction to data structures. > To look specifically at Lists, Sets, and Maps

EXAMINATIONS 2017 TRIMESTER 2

EXAMINATIONS 2011 Trimester 2, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

Dynamic Data Structures and Generics

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

CS 314 Exam 1 Fall 2017

Important Dates. Game State and Tree. Today s topics. Game Tree and Mini-Max. Games and Mini-Max 3/20/14

Building Java Programs. Interfaces and Comparable reading: , 10.2, 16.4

Class Libraries. Readings and References. Java fundamentals. Java class libraries and data structures. Reading. Other References

Generic classes & the Java Collections Framework. *Really* Reusable Code

Collections Questions

Computational Expression

CS 314 Exam 2 Spring

Test Class A. public class A { private int x, y; public int getx() { return x; } public int gety() { return y; }

Arrays. Chapter Arrays What is an Array?

Principles of Software Construction: Objects, Design and Concurrency. More design patterns and Java Collections. toad

Questions and Answers. Q.3) asses is not part of Java's collection framework?explanation:

Use of the ArrayList class

Lecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism

Unit5: Packages and abstraction

Model Solutions. COMP 103: Test April, 2013

Parametric polymorphism and Generics

COMP 103 : Test. 2019, Jan 9 ** WITH SOLUTIONS **

CSE 331. Generics (Parametric Polymorphism)

Collections Algorithms

Advanced Topics in Java and on Security in Systems Effective Generics. Eirik Eltvik 26 th of February 2007

CSE 143. Lecture 13: Interfaces, Comparable reading: , 16.4, 10.2

Sets and Maps. Part of the Collections Framework

Introduction to Collections

Interfaces. An interface defines a set of methods. An interface declaration contains signatures, but no implementations.

(f) Given what we know about linked lists and arrays, when would we choose to use one data structure over the other?

CMSC 132: Object-Oriented Programming II

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering

Today. Book-keeping. Exceptions. Subscribe to sipb-iap-java-students. Collections. Play with problem set 1

Objects and Iterators

Class 32: The Java Collections Framework

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

Implementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations

What happens if someone new wants to join our awesome club?

Homework #10 due Monday, April 16, 10:00 PM

Model Solutions. COMP 103: Test May, 2013

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1

Java Map and Set collections

ArrayList. Introduction. java.util.arraylist

Transcription:

Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani The Collection Framework

Collection: an aggregate that can hold a varying number of elements Interface: an entity that defines mandatory features (methods, attributes, etc.) of all classes that implement it EECS1020 F14 (Steven C.) 2

List add(element) remove(element) get(index) iterator()... Set add(element) remove(element) iterator()... Map add(key, value) remove(key) get(key) keyset(): Set... Sequence Set Pairs Duplicates are OK and the positional order is significant Duplicates are not allowed and order is insignificant A pair is (key,value) where key is unique EECS1020 F14 (Steven C.) 3

List add(element) remove(element) get(index) iterator()... ArrayList LinkedList Set add(element) remove(element) iterator()... HashSet TreeSet Map add(key, value) remove(key) get(key) keyset(): Set... HashMap TreeMap The two classes that implement each interface are equivalent in the client s view. The only visible diff is performance (running time). EECS1020 F14 (Steven C.) 4

ArrayList: good if you want elements to be indexed LinkedList: only efficient if elements added to the beginning of the list TreeSet or TreeMap: good if you want to access elements in sorted order HashSet or HashMap: more efficient than TreeSet/Map if you don t need sorted order EECS1020 F14 (Steven C.) 5

Java is strongly typed Object type mismatch checked at compile-time Collections prior to Java 1.5: Create for elements of a specific type Create to contain elements of type Object, then cast Java 1.5 introduced generics: Specify element type in angled brackets e.g.: <String> EECS1020 F14 (Steven C.) 6

Generics allows the element type to be defined at compilation API needs a placeholder to describe parameter types and/or return types Placeholder names are arbitrary Typical placeholders: T, E, K, V, P, C Example: add(int index, E element) EECS1020 F14 (Steven C.) 7

Declare reference using the interface, but initialize object using the class List<String> bag = new ArrayList<String>(); EECS1020 F14 (Steven C.) 8

Don t do it Generics allows for type checking at compiletime With generics: List<String> bag = new ArrayList<String>(); Without generics: List bag = new ArrayList(); Compiler warning without generics: Note: ClassName.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. EECS1020 F14 (Steven C.) 9

Use add to add elements to lists and sets: List<Date> list = new ArrayList<Date>(); Set<String> set = new HashSet<String>(); list.add(new Date()); set.add("hello"); Use put to add an element to a map Map<Integer, String> map; map = new HashMap<Integer, String>(); map.put(55, "Clock Rate"); EECS1020 F14 (Steven C.) 10

Use remove to delete from lists and sets: boolean done = set.remove("adam"); Note that remove returns false if the specified element was not found and returns true otherwise. To delete a map element given its key: String gone = map.remove(55); Note that remove in maps returns the value of the element that was removed or null if the specified key was not found. EECS1020 F14 (Steven C.) 11

The elements of lists are indexed (starting from 0). Hence, but only for lists, we can also add and delete based on the position index: To insert x at position 5: list.add(5, x); This will work only if the list has at least 5 elements, and it will adjust the indices of all elements after position 5, if any. To delete the element at position 5: list.remove(5); This will work only if the list has at least 6 elements. EECS1020 F14 (Steven C.) 12

The elements of lists and maps (but not sets) can be retrieved using get: The element at position 3 in a list: Date d = list.get(3); The value of the element with key 55 in a map: String s = map.get(55); Note: All interfaces come with size(), equals(), tostring(), and contains (containskey in maps). EECS1020 F14 (Steven C.) 13

Lists and Sets aggregate an iterator Use iterator() to get it It starts positioned before the 1 st element Use next() and hasnext() to control the cursor e 0 e 1... e n-1 EECS1020 F14 (Steven C.) 14

The Iterator class supports generics; i.e. we can obtain a type-aware iterator as follows: Iterator<String> it = set.iterator(); To benefit from this, let us rewrite the loop of the previous slide so it prints the elements capitalized: Iterator<String> it = set.iterator(); for (; it.hasnext();) { String tmp = it.next(); output.println(tmp.touppercase()); } EECS1020 F14 (Steven C.) 15

The Map interface has no iterator() method but we can obtain a set of the map s keys: public Set<K> keyset() And by iterating over the obtained set, we can, in effect, iterate over the map s elements: Iterator<Integer> it = map.keyset().iterator(); for (; it.hasnext();) { int key = it.next(); String value = map.get(key); output.println(key + " --> " + value); } EECS1020 F14 (Steven C.) 16

The Collections class has the method: static void sort(list<t> list) It rearranges the elements of the list in a non-descending order. It works if, and only if, the elements are comparable; i.e. one can invoke the compareto method on any of them passing any element as a parameter. Recall that compareto (in String) returns an int whose sign indicates < or > and whose 0 value signals equality. EECS1020 F14 (Steven C.) 17

To ensure that compareto can be invoked, we require that T (the element's class) implements Comparable<T>, an interface with only one method: compareto(t). Note: Requiring that T implements Comparable<T> is too strong. It is sufficient if T extends some class S that implements Comparable<S>. The sort method states this requirement in its API as follows: <T extends Comparable<? super T>> EECS1020 F14 (Steven C.) 18

Write a program that creates a list of a few Fractions and then sort them. List<Fraction> list; list = new ArrayList<Fraction>(); list.add(new Fraction(1,2)); list.add(new Fraction(3,4)); list.add(new Fraction(1,3)); output.println(list); Collections.sort(list); output.println(list); EECS1020 F14 (Steven C.) 19

The sort method accepts only lists. What if we needed to sort a set? Set<Fraction> set; set = new HashSet<Fraction>(); set.add(new Fraction(1,2)); set.add(new Fraction(3,4)); set.add(new Fraction(1,3)); output.println(set); A minor modification to the above program will make its output sorted EECS1020 F14 (Steven C.) 20

Simply use TreeSet instead of HashSet. The same technique applies to maps: use TreeMap instead of HashMap to keep the map's elements sorted on their keys. Note: Using a tree-implementing class for sets and maps is conceptually different from using the sort methods for lists. The former keeps the elements sorted at all times. The latter sort will not persist after adding or removing elements. EECS1020 F14 (Steven C.) 21

The main advantage of sorting is speeding up the search. When the elements are sorted, you don't have to visit all of them to determine if a given value is present in the collection or not. int binarysearch(list list, T value) The method searches for value in list and returns its index if found and a negative number otherwise Note: Unlike exhaustive search (which is linear), binary search has a complexity of O(lgN). EECS1020 F14 (Steven C.) 22

Read, study, and work through the application exercises in section 10.3 EECS1020 F14 (Steven C.) 23