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

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

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

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

Object-Oriented Programming with Java

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

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

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

DM550 Introduction to Programming part 2. Jan Baumbach.

DM550 Introduction to Programming part 2. Jan Baumbach.

CMSC 202H. Containers and Iterators

Topic 10: The Java Collections Framework (and Iterators)

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

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

Programming Languages and Techniques (CIS120)

Since it is an interface, we need a concrete class during its declaration. There are many ways to initialize a Queue object, most common being-

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

Generics Collection Framework

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

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

CS11 Java. Winter Lecture 8

Java Collections. Wrapper classes. Wrapper classes

Java Collections. Engi Hafez Seliem

PIC 20A Collections and Data Structures

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

CONTAİNERS COLLECTİONS

Collections (Java) Collections Framework

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Programming Languages and Techniques (CIS120)

Java Collections Framework reloaded

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

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

Java Collections Framework. 24 April 2013 OSU CSE 1

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

36. Collections. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Class 32: The Java Collections Framework

Announcements/Follow-ups

Java Collections Framework

Pieter van den Hombergh Richard van den Ham. February 8, 2018

Programming Languages and Techniques (CIS120)

Fundamental language mechanisms

Programming Languages and Techniques (CIS120)

Computer Science II (Spring )

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

Collections Questions

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

Java Magistère BFA

COMP6700/2140 Implementation of ADT

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

CHAPTER 7 GENERICS, COLLECTIONS, AND ALGORITHMS

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

Algorithms. Produced by. Eamonn de Leastar

Introduction to Computer Science I

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

Practical Session 3 Java Collections

Generics and collections

Collections and Maps

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

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. June 8, 2017

First Name Last Name ID#

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

Advanced Programming Generics Collections

Computational Expression

Java Data Structures Collections Framework BY ASIF AHMED CSI-211 (OBJECT ORIENTED PROGRAMMING)

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

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

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

Implementation. (Mapping to Java) Jörg Kienzle & Alfred Strohmeier. COMP-533 Implementation

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

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

Generic Collections CSC Spring 2019 Howard Rosenthal

CSE 143X. Accelerated Computer Programming I/II

Chapter 5 Java Collection. j a v a c o s q q. c o m X i a n g Z h a n g

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

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

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

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

JAVA COLLECTION FRAMEWORK & SETS

USAL1J: Java Collections. S. Rosmorduc

Java Collection Framework

Binghamton University. CS-140 Fall Interfaces

Java Collections Framework: Interfaces

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

COL106: Data Structures and Algorithms. Ragesh Jaiswal, IIT Delhi

What is the Java Collections Framework?

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

An Interface with Generics

Computational Applications in Nuclear Astrophysics using Java Java course Lecture 6

Frameworks. CS151 Chris Pollett Oct. 26, 2005.

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

Collections. James Brucker

Lecture 6 Collections

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

Objec&ves. Packages Collec&ons Generics. Sept 28, 2016 Sprenkle - CSCI209 1

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

Binghamton University. CS-140 Fall Interfaces

CS Ananda Gunawardena

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CS 3 Introduction to Software Engineering. 5: Iterators

Introduction to Collections

Tony Valderrama, SIPB IAP 2010

Transcription:

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

Online Resources Java 5 API Specification: http://java.sun.com/j2se/1.5.0/docs/api/index.html Sun Tutorial: http://java.sun.com/docs/books/tutorial/collections/ 3

Collection Interfaces Unordered Rejects duplicates Unordered Rejects duplicates Collection<E> Map<K,V> Set<E> List<E> Queue<E> SortedMap<K,V> Ordered Allows duplicates FIFO Order Allows duplicates Ordered Rejects duplicates SortedSet<E> Ordered Rejects duplicates 4

The Collection Interface Doesn t hold primitives Use wrapper classes Before Java5: Not type safe Need to use casting Since Java5: the type of the elements in the collection can be specified (using generics) collections are type-safe 5

Collection extends Iterable has only one method: Iterator<E> iterator(); Iterable<E> Collection<E> Set<E> List<E> Queue<E> SortedSet<E> 6

The Iterator Interface Provide a way to access the elements of a collection sequentially without exposing its underlying representation Methods: hasnext() - Returns true if there are more elements next() - Returns the next element remove() - Removes the last element returned by the iterator (optional operation) Command and Query 7

Iterating over a Collection for (Iterator<String> iter = collection.iterator() ; iter.hasnext( ); ) { System.out.println(iter.next()); } 8

Collection Implementations Class Name Convention: <Data structure> <Interface> General Purpose Implementations Hash Table Data Structures Resizable Array Balanced Tree Linked List Set HashSet TreeSet (SortedSet) Interfaces Queue List ArrayList LinkedList LinkedList Map HashMap TreeMap (SortedMap) 9

General Purpose Implementations No Direct Implementation Collection Map Set List Queue SortedMap SortedSet HashSet TreeSet ArrayList LinkedList HashMap TreeMap 10

Best Practice <with generics> Specify an implementation only when a collection is constructed: Set<String> s= new HashSet<String>(); Interface Implementation public void foo(hashset<string> s){ } public void foo(set<string> s) { } s.add() invokes HashSet.add() Works, but Better! polymorphism 11

How it was done before Java 5 Specify an implementation only when a collection is constructed: Set s= new HashSet (); Interface Implementation Works, but public void foo(hashset s){ } public void foo(set s) { } s.add() invokes HashSet.add() Better! polymorphism 12

Interface List Example List<Integer> list = new ArrayList<Integer>(); list.add(3); Implementation list.add(1); list.add(new Integer(1)); list.add(new Integer(6)); List holds list.remove(list.size()-1); Integer System.out.println(list); references (auto-boxing) Invokes List.toString() Output: [3, 1, 1] Insertion order is kept List allows duplicates remove() can get index or reference as argument 13

Set Example Set<Integer> set = new HashSet<Integer>(); set.add(3); A set does not allow duplicates. set.add(1); it does not contain: two references to the same object set.add(new Integer(1)); two references to null set.add(new Integer(6)); references to two objects a and b set.remove(6); such that a.equals(b) System.out.println(set); Output: [1, 3] remove() can get only reference as argument Insertion order is not guaranteed 14

Queue Example Queue<Integer> queue = new LinkedList<Integer>(); queue.add(3); queue.add(1); queue.add(new Integer(1)); queue.add(new Integer(6)); queue.remove(); System.out.println(queue); Output: [1, 1, 6] Elements are added to the tail of the queue remove() may have no argument head is removed FIFO order 15

Map Example Map<String,String> map = new HashMap<String,String>(); map.put("dan", "03-9516743"); map.put("rita", "09-5076452"); No duplicates map.put("leo", "08-5530098"); map.put("rita", "06-8201124"); System.out.println(map); Unordered Output: {Leo=08-5530098, Dan=03-9516743, Rita=06-8201124} Keys (names) Dan Rita Leo Values (phone numbers) 03-9516743 09-5076452 06-8201124 08-5530098 16

SortedMap Example SortedMap <String,String>map = new TreeMap<String,String> (); map.put("dan", "03-9516743"); map.put("rita", "09-5076452"); map.put("leo", "08-5530098"); map.put("rita", "06-8201124"); lexicographic order System.out.println(map); Output: {Dan=03-9516743, Leo=08-5530098, Rita=06-8201124} Keys (names) Dan Rita Leo Values (phone numbers) 03-9516743 06-8201124 08-5530098 17

Map Collection Views Three views of a Map as a collection keyset<k> values<v> entryset<k,v> Set Collection Set The Set of key-value pairs (implement Map.Entry) 18

Iterating Over the Keys of a Map Map<String,String> map = new HashMap<String,String> (); map.put("dan", "03-9516743"); map.put("rita", "09-5076452"); map.put("leo", "08-5530098"); map.put("rita", "06-8201124"); for (Iterator<String> iter= map.keyset().iterator(); iter.hasnext(); ) { System.out.println(iter.next()); } Output: Leo Dan Rita 19

Iterating Over the Keys of a Map Map<String,String> map = new HashMap<String,String> (); map.put("dan", "03-9516743"); map.put("rita", "09-5076452"); map.put("leo", "08-5530098"); map.put("rita", "06-8201124"); for (String key : map.keyset()) { System.out.println(key); } Output: Leo Dan Rita 20

Iterating Over the Key-Value Pairs of a Map Map<String,String> map = new HashMap<String,String> (); map.put("dan", "03-9516743"); map.put("rita", "09-5076452"); map.put("leo", "08-5530098"); map.put("rita", "06-8201124"); for (Iterator<Map.Entry<String,String>> iter= map.entryset().iterator(); iter.hasnext(); ) { Map.Entry<String,String> entry = iter.next(); System.out.println(entry.getKey() + ": " + entry.getvalue()); } Output: Leo: 08-5530098 Dan: 03-9516743 Rita: 06-8201124 21

Iterating Over the Key-Value Pairs of a Map Map<String,String> map = new HashMap<String,String> (); map.put("dan", "03-9516743"); map.put("rita", "09-5076452"); map.put("leo", "08-5530098"); map.put("rita", "06-8201124"); for (Map.Entry<String,String> entry: map.entryset()) { System.out.println(entry.getKey() + ": " + entry.getvalue()); } Output: Leo: 08-5530098 Dan: 03-9516743 Rita: 06-8201124 22

Collection Algorithms Defined in the Collections class Main algorithms: sort binarysearch reverse shuffle min max 23

Sorting import java.util.*; import the package of List, Collections and Arrays public class Sort { public static void main(string args[]) { List<String> list = Arrays.asList(args); Collections.sort(list); System.out.println(list); } } returns a List-view of its array argument. Arguments: A C D B Output: [A, B, C, D] lexicographic order 24

Sorting (cont.) Sort a List l by Collections.sort(l); If the list consists of String objects it will be sorted in lexicographic order. Why? String implements Comparable<String>: public interface Comparable<T> { public int compareto(t o); } Exception when sorting a list whose elements - do not implement Comparable or - are not mutually comparable. 25