Algorithms. Produced by. Eamonn de Leastar

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

CONTAİNERS COLLECTİONS

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

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

Sets and Maps. Part of the Collections Framework

What is the Java Collections Framework?

Lecture 6 Collections

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

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

Collections (Java) Collections Framework

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

Java Collections Framework: Interfaces

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

CS2110: Software Development Methods. Maps and Sets in Java

boolean add(object o) Method Description (from docs API ) Method Description (from docs API )

CSC 1214: Object-Oriented Programming

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

Java Collection Framework

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

Java Classes. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

9/16/2010 CS Ananda Gunawardena

CS Ananda Gunawardena

Collections, Maps and Generics

CS2110: Software Development Methods. Maps and Sets in Java

Generics Collection Framework

Class 32: The Java Collections Framework

Object-Oriented Programming in the Java language

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming

Lecture 15 Summary 3/11/2009. By the end of this lecture, you will be able to use different types of Collections and Maps in your Java code.

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

CS11 Java. Winter Lecture 8

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

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

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University

Collections and Maps

Collections. James Brucker

Java Collections. Wrapper classes. Wrapper classes

Java Collections. Engi Hafez Seliem

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List.

DM550 Introduction to Programming part 2. Jan Baumbach.

Java Control Statements

Implementing a List in Java. CSE 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List.

Java Overview An introduction to the Java Programming Language

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

1. ArrayList and Iterator in Java

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

The Java Collections Framework and Lists in Java Parts 1 & 2

An Interface with Generics

[Ref: Core Java Chp 13, Intro to Java Programming [Liang] Chp 22, Absolute Java Chp 16, docs.oracle.com/javase/tutorial/collections/toc.

Get started with the Java Collections Framework By Dan Becker

Abstract Data Types (ADTs) Example ADTs. Using an Abstract Data Type. Class #08: Linear Data Structures

Generic Programming. *Really* reusable code

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

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

Topic 10: The Java Collections Framework (and Iterators)

Java collections framework

Fall 2017 Mentoring 7: October 9, Abstract Data Types

COMP-202 Unit 7: More Advanced OOP. CONTENTS: ArrayList HashSet (Optional) HashMap (Optional)

Introduction to Collections

Introduction to Programming Using Java (98-388)

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

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

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

DM550 Introduction to Programming part 2. Jan Baumbach.

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

Computer Science II (Spring )

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

Object-Oriented Design and Programming (Java)

Garbage Collection (1)

Java collections framework

11. Collections of Objects

Programmieren II. Polymorphism. Alexander Fraser. June 4, (Based on material from T. Bögel)

EECS 2011 M: Fundamentals of Data Structures

NAME: c. (true or false) The median is always stored at the root of a binary search tree.

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

Collections of Objects. Object Oriented Programming Camilo López

Collections (Collection Framework) Sang Shin Java Technology Architect Sun Microsystems, Inc.

Today: Java Library Classes for lists. Iterators, ListIterators. CS61B Lecture #7. Last modified: Fri Sep 12 14:41: CS61B: Lecture #7 1

CSCI Object Oriented Design: Java Review Execution, I/O and New Features George Blankenship. Java Review: Execution, IO & Java 5

Java Language Features

Dynamic Data Structures and Generics

+ Abstract Data Types

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

COMP200 GENERICS. OOP using Java, from slides by Shayan Javed

More sophisticated behaviour Lecture 09

Le L c e t c ur u e e 8 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Collections

CS108, Stanford Handout #8. Java Generics

Week 4, Wednesday (Spring 2015). Dr. Yoder. Sec 051. Page 1 of 5

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

Generic types. Announcements. Raw ArrayLists. Generic types (cont.) Creating a raw ArrayList: Accessing a raw ArrayList:

Closed book but one sheet, both sides, of A4 paper is allowed. Section 2.5 of the text Generics in the Java Programming Languages by Gilad Bracha

Java Collections Framework reloaded

Tony Valderrama, SIPB IAP 2010

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

COMP-202. Generics. COMP Generics, 2013 Jörg Kienzle and others

Iterator and For-Each Loops COMP110 - Lecture 18

Collections and Iterators. Collections

Implementing a List in Java. CSC 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List CSC

Type Parameters: E - the type of elements returned by this iterator Methods Modifier and Type Method and Description

Transcription:

Algorithms Produced by Eamonn de Leastar (edeleastar@wit.ie)

Collections

± Collections Architecture ± Definition ± Architecture ± Interfaces ± Collection ± List ± Set ± Map ± Iterator ± Implementations ± ArrayList ± HashMap ± HashSet ± Java 5 Generic Collections ± Untyped vs Typed syntax ± For-each loop Overview

± Collections Architecture ± Definition ± Architecture ± Interfaces ± Collection ± List ± Set ± Map ± Iterator ± Implementations ± ArrayList ± HashMap ± HashSet ± Java 5 Generic Collections ± Untyped vs Typed syntax ± For-each loop Overview

What are Collections? ± Collections are Java objects used to store, retrieve, and manipulate other Java objects ± Any Java object may be part of a collection, so collection can contain other collections ± Collections do not store primitives ±Java collection architecture includes: ±Interfaces - abstract data types representing collections ±Implementation - concrete implementation of collection interfaces ±Algorithms - methods for manipulating collection objects

Collection Architecture ±Collection framework benefits include: ±Reusability ±Uniformity ±Faster development ±Higher quality ±Interoperability ±Less programming

Collection Architecture

Interfaces Collection uses Iterator Map uses Collection Set extends Collection (subtyping) List extends Collection (subtyping)

Interfaces ± Collections Architecture ± Definition ± Architecture ± Interfaces ± Collection ± List ± Set ± Map ± Iterator ± Implementations ± ArrayList ± HashMap ± HashSet ± Java 5 Generic Collections ± Untyped vs Typed syntax ± For-each loop

Collection Interface ± Collection represents a group of objects ± These collection objects are known as collection elements ± There is no direct implementation of this interface in JDK ± Concrete implementations are provided for subtypes ± Collections in general can allow duplicate elements, and can be ordered ± Unordered collections that allow duplicate elements should implement directly Collection interface

Adding Elements ± In general two methods are defined for adding elements to the collection: interface Collection { // /** * Adds element to the receiver. * Returns true if operation is successful, otherwise return s false. */ boolean add(object element); } /** * Adds each element from collection c to the receiver. * Returns true if operation is successful, otherwise returns false. */ boolean addall(collection c);

Removing Elements ± Similarly to adding protocol, there are two methods are defined for removing elements from the collection: interface Collection { // /** * Removes element from the receiver. * Returns true if operation is successful, otherwise returns false. */ boolean remove(object element); } /** * Removes each element contained in collection c from the receiver. * Returns true if operation is successful, otherwise returns false. */ boolean removeall(collection c);

Other Collection Methods ± Includes methods for: ± Checking how many elements are in the collection ± Checking if an element is in the collection ± Iterating through collection boolean contains(object element); boolean containsall(collection c); int size(); boolean isempty(); void clear(); boolean retainall(collection c); Iterator iterator;

Iterator Interface ± Defines a protocol for iterating through a collection: public interface Iterator { /** * Returns whether or not the underlying collection has next * element for iterating. */ boolean hasnext(); /** * Returns next element from the underlying collection. */ Object next(); } /** * Removes from the underlying collection the last element returned by next. */ void remove();

Set Interface ± Set is a collection that does not contain duplicate elements ± This is supported by additional behavior in constructors and add(), hashcode(), and equals() methods ± All constructors in a set must create a set that does not contain duplicate elements ± It is not permitted for a set to contain itself as an element ± If set element changes, and that affects equals comparisons, the behavior of a set is not specified

List Interface ± List represents an ordered collection ± Also known as sequence ± Lists may contain duplicate elements ± Lists extend behavior of collections with operations for: ± Positional Access ± Search ± List Iteration ± Range-view

Map Interface ± Map is an object that maps keys to values ± Keys must be unique, i.e. map cannot contain duplicate keys ± Each key in the map can map to most one value, i.e. one key cannot have multiple values ± Map interface defines protocols for manipulating keys and values

Collections ± Collections Architecture ± Definition ± Architecture ± Interfaces ± Collection ± List ± Set ± Map ± Iterator ± Implementations ± ArrayList ± HashMap ± HashSet ± Java 5 Generic Collections ± Untyped vs Typed syntax ± For-each loop

Most Commonly Used Collections ± Three of the most commonly used collections: ± HashSet ± ArrayList ± HashMap

ArrayList ± Represents resizable-array implementation of the List interface ± Permits all elements including null ± It is generally the best performing List interface implementation ± Instances of this class have a capacity ± It is size of the array used to store the elements in the list, and it s always at least as large as the list size ± It grows as elements are added to the list

//declare list ArrayList list = new ArrayList(); //add elements to the list list.add("first element"); list.add("second element"); //get the list size int listsize = list.size(); ArrayList Examples //print the list size and the first element System.out.println(listSize); System.out.println(list.get(0)); //add first element in the list list.add(0,"added element"); //get the list iterator Iterator iterator = list.iterator(); while (iterator.hasnext()) { String element = (String)iterator.next(); System.out.println(element); } Console 2 First element Console Added element First element Second element

HashMap ± Collection that contains pair of objects ± Values are stored at keys ± It is a hash table based implementation of the Map interface ± Permits null values and null keys ± The order of the map is not guaranteed ± Two parameters affect performance of a hash map: ± Initial capacity, indicates capacity at the map creation time ± Load factor, indicates how full the map should be before increasing its size ±0.75 is the default

HashMap Example //create a number dictionary HashMap numberdictionary = new HashMap(); numberdictionary.put("1", "One"); numberdictionary.put("2", "Two"); numberdictionary.put("3", "Three"); numberdictionary.put("4", "Four"); numberdictionary.put("5", "Five"); //get an iterator of all the keys Iterator keys = numberdictionary.keyset().iterator(); while (keys.hasnext()) { String key = (String)keys.next(); String value = (String)numberDictionary.get(key); System.out.println("Number: " + key + ", word: " + value); } Number: 5, word: Five Number: 4, word: Four Number: 3, word: Three Number: 2, word: Two Number: 1, word: One Console

HashSet ± Concrete implementation of the Set interface ± Backed up by an instance of HashMap ± Order is not guaranteed ± Performance of the set is affected by size of the set and capacity of the map ± It is important not to set the initial capacity too high, or the load factor too low if performance of iteration is important ± Elements in the set cannot be duplicated

HashSet Example //create new set HashSet set = new HashSet(); //add elements to the set set.add("one"); set.add("two"); set.add("three"); //elements cannot be duplicated in the set set.add("one"); //print the set System.out.println(set); Console [One, Three, Two]

Collections ± Collections Architecture ± Definition ± Architecture ± Interfaces ± Collection ± List ± Set ± Map ± Iterator ± Implementations ± ArrayList ± HashMap ± HashSet ± Java 5 Generic Collections ± Untyped vs Typed syntax ± For-each loop

Java 5 Generic Collection ± Collections use polymorphism to store objects of any type. ± A drawback is type loss on retrieval. ± HashMap stores key/value pairs as java Objects. ± get() method returns a matching Object for the given key. HashMap numberdictionary = new HashMap(); numberdictionary.put("1", "One"); numberdictionary.put("2", "Two"); Object value = numberdictionary.get("1 ); String strvalue = (String) value; ± The key/values in this code are actually Strings ± The return value must be type cast back to a String in order to accurately recover the stored object.

Untyped = Unsafe ± Type casting is undesirable (due to possibility of run time errors). ± Therefore, use of untyped (pre-java 5) collections is considered unsafe. ± Typed collections avoid type loss. ± Runtime checks are simplified because the type is known.

Revised syntax ± The type of object to be stored is indicated on declaration: private ArrayList<String> notes; ±... and on creation: notes = new ArrayList<String>(); ± Collection types are parameterized.

Using a typed collection ArrayList list = new ArrayList(); list.add("first element"); list.add("second element"); untyped / unsafe String first = (String)list.get(0); String second = (String)list.get(1); ArrayList<String> list = new ArrayList<String>(); list.add("first element"); list.add("second element"); String first = list.get(0); String second = list.get(1); typed / safe

Using a Typed Iteration ArrayList list = new ArrayList(); Iterator iterator = list.iterator(); while (iterator.hasnext() untyped / unsafe { String element = (String)iterator.next(); System.out.println(element); } ArrayList<String> list = new ArrayList<String>(); Iterator<String> iterator = list.iterator(); while (iterator.hasnext()) { String element = iterator.next(); System.out.println(element); } typed / safe

Typed HashMaps ±HashMaps operate with (key,value) pairs. ±A typed HashMap required two type parameters: private HashMap<String, String> responses;... responses = new HashMap<String, String> ();

HashMaps HashMap numberdictionary = new HashMap(); numberdictionary.put("1", "One"); numberdictionary.put("2", "Two"); untyped / unsafe Object value = numberdictionary.get( 1 ); String strvalue = (String) value; HashMap<String,String> numberdictionary = new HashMap<String,String>(); numberdictionary.put("1", "One"); numberdictionary.put("2", "Two"); String value = numberdictionary.get( 1 ); typed / safe

For-each Loop ± Iteration over collections is a common operation. ± If a collections provides an Iterator, Enhanced for loop simplifies code ArrayList<String> list = new ArrayList<String>(); // Iterator <String> iterator = list.iterator(); while (iterator.hasnext()) { } String element = iterator.next(); System.out.println(element); Standard while loop ArrayList<String> list = new ArrayList<String>(); // for (String element : list) { System.out.println(element); } For-each loop

Review ± Collections Architecture ± Definition ± Architecture ± Interfaces ± Collection ± List ± Set ± Map ± Iterator ± Implementations ± ArrayList ± HashMap ± HashSet ± Java 5 Generic Collections ± Untyped vs Typed syntax ± For-each loop

Except where otherwise noted, this content is licensed under a Creative Commons Attribution-NonCommercial 3.0 License. For more information, please see http:// creativecommons.org/licenses/by-nc/3.0/