Topic 10: The Java Collections Framework (and Iterators)

Size: px
Start display at page:

Download "Topic 10: The Java Collections Framework (and Iterators)"

Transcription

1 Topic 10: The Java Collections Framework (and Iterators) A set of interfaces and classes to help manage collections of data. Why study the Collections Framework? very useful in many different kinds of applications good examples of general-purpose OOP What is an Iterator? an object that helps you loop through the contents of a data structore very useful in combination with the Collections Framework 1

2 Goals For This Topic know how to use the Collections interfaces & implementations be able to make intelligent choices of interface & implementation for a particular problem Required reading: Java tutorial "trail" (link on web site) Other resources: summary sheet Java API documentation 2

3 What is a Collection? Just what it sounds like! You've already used arrays linked lists ArrayLists (part of Collections Framework) Very common problem to deal with in programming: Need to store, modify, examine a collection of things Two basic kinds of collections: sets (no duplicates, order determined by value) lists (ordered sequences -- program determines positions) A related concept: maps (dictionaries, lookup tables) 3

4 Real-Life Examples From my first real programming job, writing compilers: 1. collection of methods called by a given method 2. the statements in a method 3. symbol table: all the local variables in method, look-up by name to find type, scope, etc. 4

5 Interfaces Collection<E> Map<K,V> Set<E> List<E> SortedMap<K,V> SortedSet<E> All these are interfaces in java.util Each has at least one implementation in java.util Users can write more implementations 5

6 Java Collection Framework Interfaces, Implementations of the interfaces, and algorithms to help you use collections in your programs When you need a collection of things in a program: select an interface that provides the functionality you need select an implementation that provides good performance in your situation use additional methods from framework for sorting, searching, etc. 6

7 Possibilities For Extensions If you need something a bit different you can: create your own implementation of an interface create a sub-interface, then implement Using familiar interface => may be more useful to others. 7

8 The Collection Interface a very general interface -- operations common to all collections, details not specified recall: sets and lists are collections, maps are not Operations include: add element remove element ask if object is in collection "bulk operations" 8

9 The Set Interface a sub-interface of Collection: public interface Set<E> extends Collection<E> {... no new methods, just an addition to specifications: sets may not contain duplicate elements duplicates are defined by the equals method so if a.equals(b) is true: Set<String> myset =...; // empty set boolean flag = myset.add(a); // returns true flag = myset.add(b); // no effect, returns false Moral: remember to put equals method inside your classes 9

10 The HashSet Class implements Set, no new methods uses "hashing" technique (CISC 235) advantage: very efficient -- add, remove, search are constant time price: uses more memory than some other implementations order is arbitrary for iterators, printing Constructors: HashSet<E>(): creates an empty HashSet HashSet<E>(Collection<E> c): creates a HashSet containing all the elements of c 10

11 HashSet Example (1) Set<String> cisc121 = new HashSet<String>(); cisc121.add("john"); cisc121.add("george"); cisc121.add("paul"); cisc121.add("ringo"); System.out.println("students in cisc 121: " + cisc121); output: students in cisc 121: [Paul, John, George, Ringo] Note: elements printed in arbitrary order Set<String> cisc124 = new HashSet<String>(); cisc124.add("peter"); cisc124.add("paul"); cisc124.add("mary"); System.out.println("students in cisc 124: " + cisc124); output: students in cisc 124: [Paul, Mary, Peter] 11

12 HashSet Example (2) // look for a student if (cisc121.contains("mary")) System.out.println("Mary is taking cisc 121"); else System.out.println("Mary is not taking cisc 121"); output: Mary is not taking cisc 121 // Ringo drops out cisc121.remove("ringo"); System.out.println("new cisc 121: " + cisc121); output: new cisc 121: [Paul, John, George] 12

13 HashSet Example (3) // make a combined student list (union) Set<String> combined = new HashSet(cisc121); combined.addall(cisc124); System.out.println("combined: " + combined); output: combined: [Paul, Mary, Peter, John, George] 13

14 HashSet Example (4) // all students must attend tutorial unless they // have an A average Set<String> topofclass = new HashSet<String>(); topofclass.add("peter"); topofclass.add("paul"); // create copy of combined set Set<String> tutorial = new HashSet<String>(combined); // remove A students from set tutorial.removeall(topofclass); System.out.println("tutorial: " + tutorial); output: tutorial: [Mary, John, George] 14

15 HashSet Example (5) // find out who is taking both classes (intersection) Set<String> studentsinboth = new HashSet<String>(cisc121); studentsinboth.retainall(cisc124); System.out.println("students taking both classes: " + studentsinboth); output: students taking both classes: [Paul] 15

16 HashSet Example (6) To write a loop that does something to each set element: You need an Iterator (explained shortly). 16

17 Dangers of Hashing Hashset is a very good, efficient set implementation To use intelligently under all circumstances must understand how a hash table works CISC 235 Very safe to use for sets of String, Integers, other API classes If you create a HashSet of objects of a class you've created, you may have some surprises with: duplicate element prevention searching for a set element If time permits: more explanation later If not: stick to API classes or use a different set implementation 17

18 Two Set Implementations Collection<E> Set<E> HashSet<E> SortedSet<E> TreeSet<E> 18

19 Sorted Sets A sorted set keeps its elements in order. Advantages of TreeSet: you get elements in order for printing and iterators some extra methods: min & max elements, range subsets less memory than a HashSet Efficiency Comparison: HashSet TreeSet insert O(1) O(log n) delete O(1) O(log n) lookup O(1) O(log n) print/iterate O(n) * Time to iterate through a HashSet is proportional to the size of the table in memory 19

20 Ordering What order does a sorted set use? Normally, element type must implement Comparable. demo: TreeSetExample... Using the element type's compareto method is called using the "natural ordering". Alternative: pass a Comparator to the constructor. back to example... 20

21 Question: How Do You Loop Through a Set? Can't use a for loop -- no concept of the i-th element of a set. An Iterator is an object that helps you iterate through a collection. Goals: learn how to Use iterators -- very important 2. Write your own iterator classes -- later if time permits 21

22 Common Situation You have some kind of collection of data: array, ArrayList, linked list, stack, queue, tree, etc. You need to loop through the collection and do something with each element: print add to total change contents of objects search for a value (or set of values) check for errors etc. How you do this depends on the kind of data structure 22

23 Examples or i < count if array isn't full loop through an array: for (int i = 0; i < arr.length; i++){ // do something with arr[i] } loop through an ArrayList: for (int i = 0; i < list.size(); i++){ // do something with list.get(i) } loop through a linked list: ListCell ptr = first; while (ptr!= null) { // do something with ptr.data ptr = ptr.next } // end while 23

24 Four Common Elements Each example did four things to loop through the collection: initialize check if we're at the end of the collection access the "current" element advance to the next element 24

25 If you know the structure of your data, you know how to walk through it efficiently. Problems: Information Hiding with information hiding (private data), not always possible if you change your representation, you have to change all your loops 25

26 Java Iterator Interface An Iterator is an object that controls a loop through a data structure. Two methods in Iterator interface: hasnext(): asks "is there another element left?" next(): advances to next element and returns it The Collection interface contains this method: iterator(): returns an Iterator for looping through the collection. Look at SetIteratorExample.java. 26

27 Important Restriction You may not change a collection while an iterator is travelling through it! Try IteratorChange.java. Solution: Iterator interface has a third method: remove(). iter.remove() means "Remove the current element from the collection". Try IteratorChangeFIXED.java. 27

28 Shortcut: "For Each" Loop To avoid the Iterator syntax, Java 1.5 added a new kind of loop for simple use of an iterator. for (String item: myset) {... do something with item... } // end for Above is shorthand for: Iterator<String> iter = myset.iterator(); while (iter.hasnext()) { String item = iter.next();... do something with item... } // end while Look at ForEachLoop.java 28

29 Limitations of "For Each" "For each" loops are great for many purposes. Two limitations: can't modify the collection during the loop only one kind of iterator for a collection type 29

30 The List Interface Collection<E> List<E> ArrayList<E> LinkedList<E> Lists are different from Sets because: programmer specifies order of elements duplicates are OK Every element has a position: 0, 1, 2,..., size-1 30

31 List Methods List inherits all methods from Collection. add with just one parameter (from Collection): adds to end of list add with two parameters (new): first parameter is index More new List methods: get/set/remove by index sublist by index range search returning index, not just boolean fancy iterators 31

32 List Implementations Two implementations: ArrayList, LinkedList Same methods available; only difference is performance. Advantages of ArrayList: random access get(i) is O(1) adding to / deleting from end of list is O(1) Advantage of LinkedList: adding to / deleting from either end is O(1) demo: ListExample Uses ArrayList. You could substitute LinkedList in declarations and results wouldn't change 32

33 Collections Class The Collections class provides several useful static methods Some examples: static void shuffle(list l); static void sort(list l); static void sort(list l, Comparator c); static Object max(collection coll) static Object max(collection coll, Comparator comp) static Object min(collection coll) static Object min(collection coll, Comparator comp) 33

34 Collections & Aliases Very important facts to remember: A Collection of Objects is really a Collection of references to Objects (pointers) When you add an Object to a Collection, it does not make a copy. If an Object belongs to several collections, all the collections contain references to the same Object. 34

35 Example Person peter = new Person("Peter", 20); Person paul = new Person("Paul", 20); Person mary = new Person("Mary", 20); Set<Person> cisc121 = new HashSet<Person>(); cisc121.add(peter); cisc121.add(paul); Set<Person> cisc124 = new HashSet<Person>(); cisc124.add(paul); cisc124.add(mary); for (Person p: cisc121) p.age++; for (Person p: cisc124) p.age++; System.out.println(peter); System.out.println(paul); System.out.println(mary); 35

36 Exceptions Many Collection methods can throw exceptions. Most are sub-classes of RuntimeException, so don't have to catch. Try to prevent with careful programming. See Java API descriptions for details Example: List mylist = new LinkedList(); // or ArrayList... // mylist.size() is now 5 Object o = mylist.get(6); // exception! 36

37 Maps A map is like a "dict" in Python. Set of <key,value> pairs -- a "mapping" from each key to a value. Examples: phone book student database organized by student number 37

38 HashMap Implementation A good, efficient implementation using hashing Most operations are O(1) -- independent of size of table. like HashSet, doesn't maintain entries in any logical order Often use simple API types for keys (String, Integer) -- these are OK. Using own classes as keys: wait for explanation or use different map implementation 38

39 HashMap Example (1) Use simple class for marks: class Marks { int midterm; // midterm mark int finalexam; // final exam mark // plus obvious constructor & tostring } // Create a map from student name to Marks Map<String, Marks> studentmap = new HashMap<String, Marks>(); studentmap.put("buffy", new Marks(63, 71)); studentmap.put("willow", new Marks(97, 98)); studentmap.put("xander", new Marks(42, 37)); // Fix error in Buffy's marks studentmap.put("buffy", new Marks(64, 71)); 39

40 HashMap Example (2) // retrieve Buffy's marks Marks buffymarks = studentmap.get("buffy"); if (buffymarks!= null) System.out.println("Buffy's marks are: " + buffymarks); else System.out.println("no marks for Buffy"); output: Buffy's marks are: (64,71) // look for Dawn's marks (not there) Marks dawnmarks = studentmap.get("dawn"); if (dawnmarks!= null) System.out.println("Dawn's marks are: " + dawnmarks); else System.out.println("no marks for Dawn"); output: no marks for Dawn 40

41 Sorted Maps Distinction between regular maps & sorted maps just like set vs. sorted set In a sorted map: elements will print in order (by key) iterators will return elements in order you get a few additional methods Implementation: TreeMap Must either: use class for keys that implements Comparable supply a Comparator 41

42 Other Ways to View Maps Common question: how do you iterate over a map? Instead of iterators, API provides alternate views of a map: can iterate over those views "key set": set of all the keys in the map. This is not a copy if you remove element from set, you've removed that key from the map Not allowed to add to a key set just remove. demo: MapIteratorDemo.java 42

43 Entry Sets A map may be thought of as a set of pairs: (key, value) Use entryset method to view a map as a set of pairs. Will return a Set of objects of that implement this interface: interface Entry<K,V> { K getkey(); V getvalue(); V setvalue(v value); } May not add elements to entry set. May delete elements and change values. demo... 43

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

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

More information

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

Software 1 with Java. Recitation No. 6 (Collections) Software 1 with Java Recitation No. 6 (Collections) Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework Interfaces Implementations Algorithms 2

More information

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

Software 1 with Java. Java Collections Framework. Collection Interfaces. Online Resources. The Collection Interface Java Collections Framework Collection: a group of elements Based Design: Software 1 with Java Java Collections Framework s s Algorithms Recitation No. 6 (Collections) 2 Collection s Online Resources Collection

More information

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

Abstract data types (again) Announcements. Example ADT an integer bag (next) The Java Collections Framework Announcements Abstract data types (again) PS 5 ready Tutoring schedule updated with more hours Today s topic: The Java Collections Framework Reading: Section 7.5 An ADT is a model of a collection of data

More information

Sets and Maps. Part of the Collections Framework

Sets and Maps. Part of the Collections Framework Sets and Maps Part of the Collections Framework The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection int size( ); boolean isempty( ); boolean contains(object

More information

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

Today. Book-keeping. Exceptions. Subscribe to sipb-iap-java-students.  Collections. Play with problem set 1 Today Book-keeping Exceptions Subscribe to sipb-iap-java-students Collections http://sipb.mit.edu/iap/java/ Play with problem set 1 No class Monday (MLK); happy Hunting Problem set 2 on Tuesday 1 2 So

More information

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

EXAMINATIONS 2011 Trimester 2, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW V I C T O R I A UNIVERSITY OF WELLINGTON Student ID:....................... EXAMINATIONS 2011 Trimester 2, MID-TERM TEST COMP103 Introduction

More information

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

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures Collections CSE 143 Java Collections Most programs need to store and access collections of data Collections are worth studying because... They are widely useful in programming They provide examples of

More information

CS11 Java. Winter Lecture 8

CS11 Java. Winter Lecture 8 CS11 Java Winter 2010-2011 Lecture 8 Java Collections Very powerful set of classes for managing collections of objects Introduced in Java 1.2 Provides: Interfaces specifying different kinds of collections

More information

Object-Oriented Programming with Java

Object-Oriented Programming with Java Object-Oriented Programming with Java Recitation No. 2 Oranit Dror The String Class Represents a character string (e.g. "Hi") Explicit constructor: String quote = "Hello World"; string literal All string

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 27 Mar 23, 2012 Generics, CollecBons and IteraBon Announcements CIS Course Faire TODAY at 3PM, here HW08 is due on Monday, at 11:59:59pm Midterm 2

More information

Model Solutions. COMP 103: Test April, 2013

Model Solutions. COMP 103: Test April, 2013 Family Name:............................. Other Names:............................. ID Number:............................... Signature.................................. Instructions Time allowed: 40 minutes

More information

Class 26: Linked Lists

Class 26: Linked Lists Introduction to Computation and Problem Solving Class 26: Linked Lists Prof. Steven R. Lerman and Dr. V. Judson Harward 2 The Java Collection Classes The java.util package contains implementations of many

More information

Java Map and Set collections

Java Map and Set collections Java Map and Set collections Java Set container idea interface Java Map container idea interface iterator concordance example Java maps and sets [Bono] 1 Announcements This week s lab based on an example

More information

CMSC 202H. Containers and Iterators

CMSC 202H. Containers and Iterators CMSC 202H Containers and Iterators Container Definition A container is a data structure whose purpose is to hold objects. Most languages support several ways to hold objects Arrays are compiler-supported

More information

EXAMINATIONS 2017 TRIMESTER 2

EXAMINATIONS 2017 TRIMESTER 2 T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW VICTORIA U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2017 TRIMESTER 2 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

More information

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

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1 Topic #9: Collections CSE 413, Autumn 2004 Programming Languages http://www.cs.washington.edu/education/courses/413/04au/ If S is a subtype of T, what is S permitted to do with the methods of T? Typing

More information

CS2110: Software Development Methods. Maps and Sets in Java

CS2110: Software Development Methods. Maps and Sets in Java CS2110: Software Development Methods Maps and Sets in Java These slides are to help with the lab, Finding Your Way with Maps This lab uses Maps, and Sets too (but just a little). Readings from textbook:

More information

Java Collections Framework. 24 April 2013 OSU CSE 1

Java Collections Framework. 24 April 2013 OSU CSE 1 Java Collections Framework 24 April 2013 OSU CSE 1 Overview The Java Collections Framework (JCF) is a group of interfaces and classes similar to the OSU CSE components The similarities will become clearly

More information

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

Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani. The Collection Framework 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:

More information

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

תוכנה 1 מבני נתונים גנריים תוכנה 1 מבני נתונים גנריים תרגול 8 Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework Interfaces Implementations Algorithms 2 Online Resources

More information

Java Review: Objects

Java Review: Objects Outline Java review Abstract Data Types (ADTs) Interfaces Class Hierarchy, Abstract Classes, Inheritance Invariants Lists ArrayList LinkedList runtime analysis Iterators Java references 1 Exam Preparation

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 28 April 2, 2014 Generics and CollecCons Midterm 2 is Friday Announcements Towne 100 last names A - L DRLB A1 last names M - Z Review sessions: Tonight!

More information

What is the Java Collections Framework?

What is the Java Collections Framework? 1 of 13 What is the Java Collections Framework? To begin with, what is a collection?. I have a collection of comic books. In that collection, I have Tarzan comics, Phantom comics, Superman comics and several

More information

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

Adam Blank Lecture 5 Winter 2019 CS 2. Introduction to Programming Methods Adam Blank Lecture 5 Winter 2019 CS 2 Introduction to Programming Methods CS 2: Introduction to Programming Methods Java Collections Abstract Data Types (ADT) 1 Abstract Data Type An abstract data type

More information

CS61BL Summer 2013 Midterm 2

CS61BL Summer 2013 Midterm 2 CS61BL Summer 2013 Midterm 2 Sample Solutions + Common Mistakes Question 0: Each of the following cost you.5 on this problem: you earned some credit on a problem and did not put your five digit on the

More information

Model Solutions. COMP 103: Test May, 2013

Model Solutions. COMP 103: Test May, 2013 Family Name:............................. Other Names:............................. ID Number:............................... Signature.................................. Instructions Time allowed: 45 minutes

More information

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

SUMMARY INTRODUCTION COLLECTIONS FRAMEWORK. Introduction Collections and iterators Linked list Array list Hash set Tree set Maps Collections framework SUMMARY COLLECTIONS FRAMEWORK PROGRAMMAZIONE CONCORRENTE E DISTR. Università degli Studi di Padova Dipartimento di Matematica Corso di Laurea in Informatica, A.A. 2015 2016 Introduction Collections and

More information

5 More sophisticated behavior

5 More sophisticated behavior Main concepts to be covered 5 More sophisticated behavior Using library classes to implement some more advanced functionality BK Chap. 6 Maps and sets Random number generation Equality vs identity Class

More information

EXAMINATIONS 2010 END YEAR. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

EXAMINATIONS 2010 END YEAR. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW V I C T O R I A UNIVERSITY OF WELLINGTON Student ID:....................... EXAMINATIONS 2010 END YEAR COMP103 Introduction to Data

More information

DM550 Introduction to Programming part 2. Jan Baumbach.

DM550 Introduction to Programming part 2. Jan Baumbach. DM550 Introduction to Programming part 2 Jan Baumbach jan.baumbach@imada.sdu.dk http://www.baumbachlab.net Sorting Tree Balancing A sorted tree is balanced iff for each node holds: Math.abs(size(node.left)

More information

Class 32: The Java Collections Framework

Class 32: The Java Collections Framework Introduction to Computation and Problem Solving Class 32: The Java Collections Framework Prof. Steven R. Lerman and Dr. V. Judson Harward Goals To introduce you to the data structure classes that come

More information

EXAMINATIONS 2016 TRIMESTER 2

EXAMINATIONS 2016 TRIMESTER 2 T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW VICTORIA U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2016 TRIMESTER 2 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

More information

U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2018 TRIMESTER 2 COMP 103 PRACTICE EXAM

U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2018 TRIMESTER 2 COMP 103 PRACTICE EXAM T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW VICTORIA U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2018 TRIMESTER 2 COMP 103 PRACTICE EXAM Time Allowed: TWO HOURS ********

More information

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS T E W H A R E W Ā N A N G A O T E Student ID:....................... Ū P O K O O T E I K A A M Ā U I VUW VICTORIA U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2015 TRIMESTER 2 COMP103 INTRODUCTION

More information

Java Collections Framework

Java Collections Framework Java Collections Framework Introduction In this article from my free Java 8 course, you will be given a high-level introduction of the Java Collections Framework (JCF). The term Collection has several

More information

Collections and Maps

Collections and Maps Software and Programming I Collections and Maps Roman Kontchakov / Carsten Fuhs Birkbeck, University of London Outline Array Lists Enhanced for Loop ArrayList and LinkedList Collection Interface Sets and

More information

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

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , CSE 143 Lecture 26 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, 15.3-15.4, 16.4-16.5 slides created by Marty Stepp, adapted by Alyssa Harding

More information

Collections Framework: Part 2

Collections Framework: Part 2 Collections Framework: Part 2 Computer Science and Engineering College of Engineering The Ohio State University Lecture 18 Collection Implementations Java SDK provides several implementations of Collection

More information

CONTAİNERS COLLECTİONS

CONTAİNERS COLLECTİONS CONTAİNERS Some programs create too many objects and deal with them. In such a program, it is not feasible to declare a separate variable to hold reference to each of these objects. The proper way of keeping

More information

EXAMINATIONS 2012 MID YEAR. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

EXAMINATIONS 2012 MID YEAR. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW V I C T O R I A UNIVERSITY OF WELLINGTON Student ID:....................... EXAMINATIONS 2012 MID YEAR COMP103 Introduction to Data

More information

Computer Science II (Spring )

Computer Science II (Spring ) Computer Science II 4003-232-01 (Spring 2007-2008) Week 5: Generics, Java Collection Framework Richard Zanibbi Rochester Institute of Technology Generic Types in Java (Ch. 21 in Liang) What are Generic

More information

COMP 103 : Test. 2018, Sept 12//(Corrected) ** WITH SOLUTIONS

COMP 103 : Test. 2018, Sept 12//(Corrected) ** WITH SOLUTIONS Family Name:.............................. Other Names:............................. Student ID:................................ Signature.................................. COMP 103 : Test 2018, Sept 12//(Corrected)

More information

SOLUTIONS. COMP103 Introduction to Data Structures and Algorithms

SOLUTIONS. COMP103 Introduction to Data Structures and Algorithms T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW V I C T O R I A UNIVERSITY OF WELLINGTON Student ID:....................... EXAMINATIONS 2011 MID YEAR COMP103 Introduction to Data

More information

PIC 20A Collections and Data Structures

PIC 20A Collections and Data Structures PIC 20A Collections and Data Structures Ernest Ryu UCLA Mathematics Last edited: March 14, 2018 Introductory example How do you write a phone book program? Some programmers may yell hash table! and write

More information

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

Today's Agenda. > To give a practical introduction to data structures. > To look specifically at Lists, Sets, and Maps Today's Agenda > To give a practical introduction to data structures > To look specifically at Lists, Sets, and Maps > To talk briefly about Generics in Java > To talk about interfaces in Java Data Structures

More information

Model Solutions. COMP 103: Mid-term Test. 19th of August, 2016

Model Solutions. COMP 103: Mid-term Test. 19th of August, 2016 Family Name:............................. Other Names:............................. ID Number:............................... Signature.................................. Instructions Time allowed: 45 minutes

More information

Question 0. (1 point) Write the correct ID of the section you normally attend on the cover page of this exam if you have not already done so.

Question 0. (1 point) Write the correct ID of the section you normally attend on the cover page of this exam if you have not already done so. CSE 143 Sp04 Midterm 2 Page 1 of 10 Reference information about some standard Java library classes appears on the last pages of the test. You can tear off these pages for easier reference during the exam

More information

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

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering Readings and References Java Collections "Collections", Java tutorial http://java.sun.com/docs/books/tutorial/collections/index.html CSE 403, Spring 2004 Software Engineering http://www.cs.washington.edu/education/courses/403/04sp/

More information

Lists and Iterators. CSSE 221 Fundamentals of Software Development Honors Rose-Hulman Institute of Technology

Lists and Iterators. CSSE 221 Fundamentals of Software Development Honors Rose-Hulman Institute of Technology Lists and Iterators CSSE 221 Fundamentals of Software Development Honors Rose-Hulman Institute of Technology Announcements Should be making progress on VectorGraphics. Should have turned in CRC cards,

More information

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

תוכנה 1 מבני נתונים גנריים תוכנה 1 מבני נתונים גנריים תרגול 8 2 Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework Interfaces Implementations Algorithms 3 Online Resources

More information

Model Solutions. COMP 103: Mid-term Test. 21st of August, 2014

Model Solutions. COMP 103: Mid-term Test. 21st of August, 2014 Family Name:............................. Other Names:............................. ID Number:............................... Signature.................................. Instructions Time allowed: 50 minutes

More information

Algorithms. Produced by. Eamonn de Leastar

Algorithms. Produced by. Eamonn de Leastar Algorithms Produced by Eamonn de Leastar (edeleastar@wit.ie) Collections ± Collections Architecture ± Definition ± Architecture ± Interfaces ± Collection ± List ± Set ± Map ± Iterator ± Implementations

More information

A simple map: Hashtable

A simple map: Hashtable Using Maps A simple map: Hashtable To create a Hashtable, use: import java.util.*; Hashtable table = new Hashtable(); To put things into a Hashtable, use: table.put(key, value); To retrieve a value from

More information

Java Collections. Readings and References. Collections Framework. Java 2 Collections. References. CSE 403, Winter 2003 Software Engineering

Java Collections. Readings and References. Collections Framework. Java 2 Collections. References. CSE 403, Winter 2003 Software Engineering Readings and References Java Collections References» "Collections", Java tutorial» http://java.sun.com/docs/books/tutorial/collections/index.html CSE 403, Winter 2003 Software Engineering http://www.cs.washington.edu/education/courses/403/03wi/

More information

EXAMINATIONS 2006 SUMMER TRIMESTER. COMP103 Introduction to Data Structures and Algorithms

EXAMINATIONS 2006 SUMMER TRIMESTER. COMP103 Introduction to Data Structures and Algorithms T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I ÎÍÏ V I C T O R I A UNIVERSITY OF WELLINGTON EXAMINATIONS 2006 SUMMER TRIMESTER COMP103 Introduction to Data Structures and Algorithms

More information

Collections, Maps and Generics

Collections, Maps and Generics Collections API Collections, Maps and Generics You've already used ArrayList for exercises from the previous semester, but ArrayList is just one part of much larger Collections API that Java provides.

More information

COMP103 Test. 5 Sept, 2007

COMP103 Test. 5 Sept, 2007 Family Name:.......................... Other Names:.......................... ID Number:............................ COMP103 Test 5 Sept, 2007 Instructions Time: 90 minutes. Answer all the questions. There

More information

JAVA COLLECTION FRAMEWORK & SETS

JAVA COLLECTION FRAMEWORK & SETS JAVA COLLECTION FRAMEWORK & SETS Ch07.4-5 & Ch10.5 Presentation for use with the textbook 1. Data Structures and Algorithms in Java, 6 th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser,

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 27 March 23 rd, 2016 Generics and Collections Chapter 25 HW #6 due Tuesday Announcements I will be away all next week (FP workshop in Germany) Monday's

More information

Hashing. Reading: L&C 17.1, 17.3 Eck Programming Course CL I

Hashing. Reading: L&C 17.1, 17.3 Eck Programming Course CL I Hashing Reading: L&C 17.1, 17.3 Eck 10.3 Defne hashing Objectives Discuss the problem of collisions in hash tables Examine Java's HashMap implementation of hashing Look at HashMap example Save serializable

More information

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

COMP 103 : Test. 2019, Jan 9 ** WITH SOLUTIONS ** Family Name:.............................. Other Names:...................................... Signature.................................. COMP 103 : Test 2019, Jan 9 ** WITH SOLUTIONS ** Instructions Time

More information

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

Adam Blank Lecture 9 Autumn 2016 CSE 143. Computer Programming II Adam Blank Lecture 9 Autumn 2016 CSE 143 Computer Programming II CSE 143: Computer Programming II Sets and Maps Outline 1 Sets 2 Foreach Loops 3 Maps Alice in Wonderland 1 Count the Number of Distinct

More information

An Interface with Generics

An Interface with Generics Generics CSC207 Software Design Generics An Interface with Generics Generics class foo introduces a class with a type parameter T. introduces a type parameter that is required to be

More information

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120) Programming Languages and Techniques (CIS120) Lecture 27 March 28, 2018 Java Generics Collections and Equality Chapters 25 & 26 Announcements HW7: Chat Server Available on Codio / Instructions on the web

More information

CS 314 Midterm 2 Fall 2012

CS 314 Midterm 2 Fall 2012 Points off 1 2 3 4 5 Total off Net Score CS 314 Midterm 2 Fall 2012 Your Name_ Your UTEID Circle yours TA s name: John Zihao Instructions: 1. There are 5 questions on this test. 2. You have 2 hours to

More information

Java Magistère BFA

Java Magistère BFA Java 101 - Magistère BFA Lesson 4: Generic Type and Collections Stéphane Airiau Université Paris-Dauphine Lesson 4: Generic Type and Collections (Stéphane Airiau) Java 1 Linked List 1 public class Node

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

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

EXAMINATIONS 2012 Trimester 1, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW V I C T O R I A UNIVERSITY OF WELLINGTON Student ID:....................... EXAMINATIONS 2012 Trimester 1, MID-TERM TEST COMP103 Introduction

More information

INTRODUCTION TO DATA AND PROCEDURE

INTRODUCTION TO DATA AND PROCEDURE INTRODUCTION TO DATA AND PROCEDURE In this book, our goal is to understand computation. In particular, we want to be able to take any computational problem and produce a technique for solving it that is

More information

Review. CSE 143 Java. A Magical Strategy. Hash Function Example. Want to implement Sets of objects Want fast contains( ), add( )

Review. CSE 143 Java. A Magical Strategy. Hash Function Example. Want to implement Sets of objects Want fast contains( ), add( ) Review CSE 143 Java Hashing Want to implement Sets of objects Want fast contains( ), add( ) One strategy: a sorted list OK contains( ): use binary search Slow add( ): have to maintain list in sorted order

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 11 Sets and Maps reading: 11.2-11.3 2 Languages and Grammars 4 Languages and grammars (formal) language: A set of words or symbols. grammar: A description of a language that

More information

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

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss The Collections API Mark Allen Weiss Lecture Objectives To learn how to use the Collections package in Java 1.2. To illustrate features of Java that help (and hurt) the design of the Collections API. Tuesday,

More information

COMP 103 : Test. 2018, Sept 12//(Corrected)

COMP 103 : Test. 2018, Sept 12//(Corrected) Family Name:.............................. Other Names:............................. Student ID:................................ Signature.................................. COMP 103 : Test 2018, Sept 12//(Corrected)

More information

DM550 Introduction to Programming part 2. Jan Baumbach.

DM550 Introduction to Programming part 2. Jan Baumbach. DM550 Introduction to Programming part 2 Jan Baumbach jan.baumbach@imada.sdu.dk http://www.baumbachlab.net MULTIVARIATE TREES 2 Multivariate Trees general class of trees nodes can have any number of children

More information

COMP6700/2140 Abstract Data Types: Queue, Set, Map

COMP6700/2140 Abstract Data Types: Queue, Set, Map COMP6700/2140 Abstract Data Types: Queue, Set, Map Alexei B Khorev and Josh Milthorpe Research School of Computer Science, ANU 19 April 2017 Alexei B Khorev and Josh Milthorpe (RSCS, ANU) COMP6700/2140

More information

Java HashMap Interview Questions

Java HashMap Interview Questions Java HashMap Interview Questions codespaghetti.com/java-hashmap-interview-questions/ HashMap Java HashMap Interview Questions, Algorithms and Programs. Table of Contents: CHAPTER 1: Java HashMap Interview

More information

COMP6700/2140 Implementation of ADT

COMP6700/2140 Implementation of ADT COMP6700/2140 Implementation of ADT Alexei B Khorev and Josh Milthorpe Research School of Computer Science, ANU May 2017 Alexei B Khorev and Josh Milthorpe (RSCS, ANU) COMP6700/2140 Implementation of ADT

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 11 Lecture 11-1: Sets and Maps reading: 11.2-11.3 2 Exercise Write a program that counts the number of unique words in a large text file (say, Moby Dick or the King James

More information

CSC 321: Data Structures. Fall 2016

CSC 321: Data Structures. Fall 2016 CSC 321: Data Structures Fall 2016 Balanced and other trees balanced BSTs: AVL trees, red-black trees TreeSet & TreeMap implementations heaps priority queue implementation heap sort 1 Balancing trees recall:

More information

CSC 321: Data Structures. Fall 2017

CSC 321: Data Structures. Fall 2017 CSC 321: Data Structures Fall 2017 Balanced and other trees balanced BSTs: AVL trees, red-black trees TreeSet & TreeMap implementations heaps priority queue implementation heap sort 1 Balancing trees recall:

More information

COMP 103 Introduction to Data Structures and Algorithms

COMP 103 Introduction to Data Structures and Algorithms T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW V I C T O R I A UNIVERSITY OF WELLINGTON Student ID:..................... EXAMINATIONS 2005 END-YEAR COMP 103 Introduction to Data

More information

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Inheritance Abstract classes Interfaces instanceof operator Nested classes Enumerations COUSE CONTENT Collections List Map Set Aggregate

More information

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

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 Iterators 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 9-2 2-2 What is an Iterator? An iterator is an abstract data

More information

Computer Science 62. Midterm Examination

Computer Science 62. Midterm Examination Computer Science 62 Bruce/Mawhorter Fall 16 Midterm Examination October 5, 2016 Question Points Score 1 15 2 10 3 10 4 8 5 9 TOTAL 52 Your name (Please print) 1. Suppose you are given a singly-linked list

More information

Main loop structure. A Technical Support System. The exit condition. Main loop body

Main loop structure. A Technical Support System. The exit condition. Main loop body Main concepts to be covered More sophisticated behavior Using library classes Reading documentation Using library classes to implement some more advanced functionality 5.0 2 The Java class library Thousands

More information

CSE 143X. Accelerated Computer Programming I/II

CSE 143X. Accelerated Computer Programming I/II Adam Blank Lecture 17 Autumn 2015 CSE 143X Accelerated Computer Programming I/II CSE 143X: Accelerated Computer Programming I/II Sets and Maps Outline 1 Languages and Grammars 2 Sets 3 Foreach Loops 4

More information

CS2110: Software Development Methods. Maps and Sets in Java

CS2110: Software Development Methods. Maps and Sets in Java CS2110: Software Development Methods Maps and Sets in Java These slides are to help with the lab, Finding Your Way with Maps Today s lab uses Maps (and Sets but just a little). Readings from textbook:

More information

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

17. Java Collections. Organizing Data. Generic List in Java: java.util.list. Type Parameters ( Parameteric Polymorphism ) Data Structures that we know Organizing Data Data Structures that we know 17 Java Collections Generic Types, Iterators, Java Collections, Iterators Today: Arrays Fixed-size sequences Strings Sequences of characters Linked Lists (up

More information

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

Class Libraries. Readings and References. Java fundamentals. Java class libraries and data structures. Reading. Other References Reading Readings and References Class Libraries CSE 142, Summer 2002 Computer Programming 1 Other References» The Java tutorial» http://java.sun.com/docs/books/tutorial/ http://www.cs.washington.edu/education/courses/142/02su/

More information

CITS1001 week 6 Libraries

CITS1001 week 6 Libraries CITS1001 week 6 Libraries Arran Stewart April 12, 2018 1 / 52 Announcements Project 1 available mid-semester test self-assessment 2 / 52 Outline Using library classes to implement some more advanced functionality

More information

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

Implementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations Readings List Implementations Chapter 20.2 Objectives Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations Additional references:

More information

Announcements. Container structures so far. IntSet ADT interface. Sets. Today s topic: Hashing (Ch. 10) Next topic: Graphs. Break around 11:45am

Announcements. Container structures so far. IntSet ADT interface. Sets. Today s topic: Hashing (Ch. 10) Next topic: Graphs. Break around 11:45am Announcements Today s topic: Hashing (Ch. 10) Next topic: Graphs Break around 11:45am Container structures so far Array lists O(1) access O(n) insertion/deletion (average case), better at end Linked lists

More information

EXAMINATIONS 2005 END-YEAR. COMP 103 Introduction to Data Structures and Algorithms

EXAMINATIONS 2005 END-YEAR. COMP 103 Introduction to Data Structures and Algorithms T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I ÎÍÏ V I C T O R I A UNIVERSITY OF WELLINGTON EXAMINATIONS 2005 END-YEAR COMP 103 Introduction to Data Structures and Algorithms Time Allowed:

More information

CSE 373. Java Collection Framework. reading: Weiss Ch. 3, 4.8. slides created by Marty Stepp

CSE 373. Java Collection Framework. reading: Weiss Ch. 3, 4.8. slides created by Marty Stepp CSE 373 Java Collection Framework reading: Weiss Ch. 3, 4.8 slides created by Marty Stepp http://www.cs.washington.edu/373/ 1 Arrays array: An object that stores many values of the same type. element:

More information

Garbage Collection (1)

Garbage Collection (1) Coming up: Today: Finish unit 6 (garbage collection) start ArrayList and other library objects Wednesday: Complete ArrayList, basics of error handling Friday complete error handling Next week: Recursion

More information

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp DM550 / DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ ABSTRACT DATATYPES 2 Abstract Datatype (ADT)

More information

Collections. James Brucker

Collections. James Brucker Collections James Brucker Collection A Collection is a group of objects. Set an unordered collection no duplicates List ordered collection duplicates are allowed can add or remove elements anywhere in

More information

Generics Collection Framework

Generics Collection Framework Generics Collection Framework Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 Generics

More information

COMP-202: Foundations of Programming. Lecture 26: Review; Wrap-Up Jackie Cheung, Winter 2016

COMP-202: Foundations of Programming. Lecture 26: Review; Wrap-Up Jackie Cheung, Winter 2016 COMP-202: Foundations of Programming Lecture 26: Review; Wrap-Up Jackie Cheung, Winter 2016 Announcements Final is scheduled for Apr 21, 2pm 5pm GYM FIELD HOUSE Rows 1-21 Please submit course evaluations!

More information