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

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

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

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

Object-Oriented Programming with Java

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

DM550 Introduction to Programming part 2. Jan Baumbach.

DM550 Introduction to Programming part 2. Jan Baumbach.

Generics Collection Framework

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

CMSC 202H. Containers and Iterators

Java Collections Framework. 24 April 2013 OSU CSE 1

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

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

PIC 20A Collections and Data Structures

Topic 10: The Java Collections Framework (and Iterators)

Java Magistère BFA

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

Java Collections Framework

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

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

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

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

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-

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

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

CONTAİNERS COLLECTİONS

An Interface with Generics

Collections (Java) Collections Framework

[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 reloaded

Collections Framework: Part 2

Class 32: The Java Collections Framework

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

Advanced Programming Generics Collections

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

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

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

Computational Applications in Nuclear Astrophysics using Java Java course Lecture 6

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Computer Science II (Spring )

Collections and Maps

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

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

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

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

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

Programming Languages and Techniques (CIS120)

Fundamental language mechanisms

Frameworks. CS151 Chris Pollett Oct. 26, 2005.

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

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

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

Programming Languages and Techniques (CIS120)

CHAPTER 7 GENERICS, COLLECTIONS, AND ALGORITHMS

First Name Last Name ID#

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

Sets and Maps. CSE260, Computer Science B: Honors Stony Brook University

Java Collections. Wrapper classes. Wrapper classes

Java Collections. Engi Hafez Seliem

Practical Session 3 Java Collections

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

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

CSE 143X. Accelerated Computer Programming I/II

Generics and collections

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

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

11/27/12. CS202 Fall 2012 Lecture 11/15. Hashing. What: WiCS CS Courses: Inside Scoop When: Monday, Nov 19th from 5-7pm Where: SEO 1000

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

Generic Collections CSC Spring 2019 Howard Rosenthal

CS11 Java. Winter Lecture 8

Sets and Maps. Part of the Collections Framework

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

COMP6700/2140 Implementation of ADT

EXAMINATIONS 2016 TRIMESTER 2

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

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

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

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

Java Collection Framework

USAL1J: Java Collections. S. Rosmorduc

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

What is the Java Collections Framework?

Collections Questions

EXAMINATIONS 2017 TRIMESTER 2

Advanced Programming Languages Effective Java Item 1. Spring 2015 Chungnam National Univ Eun-Sun Cho

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

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

JAVA. java.lang.stringbuffer java.lang.stringbuilder

CS Ananda Gunawardena

Model Solutions. COMP 103: Test April, 2013

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

EPITA Première Année Cycle Ingénieur. Atelier Java - J2

Strings and Arrays. Hendrik Speleers

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

Tony Valderrama, SIPB IAP 2010

Binghamton University. CS-140 Fall Interfaces

Algorithms. Produced by. Eamonn de Leastar

Chapter 5 Java Collection. Wang Yang

Transcription:

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

Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework Interfaces Implementations Algorithms 2

Online Resources Java 7 API Specification: http://docs.oracle.com/javase/7/docs/api/ The Collections framework is in java.util Oracle Tutorial: http://docs.oracle.com/javase/tutorial/collections/ 3

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

A Simple Example Collection<String> stringcollection = Collection<Integer> integercollection = stringcollection.add("hello"); integercollection.add(5); integercollection.add(new Integer(6)); stringcollection.add(7); integercollection.add("world"); stringcollection = integercollection; 5

A Simple Example Collection<String> stringcollection = Collection<Integer> integercollection = stringcollection.add("hello"); integercollection.add(5); מצביעים ל Collection של מחרוזות ושל מספרים Collection אינו מחזיק טיפוסים פרימיטיביים, לכן נשתמש ב Float,Double,Integer וכדומה נראה בהמשך אילו מחלקות מממשות מנשק זה integercollection.add(new Integer(6)); stringcollection.add(7); integercollection.add("world"); stringcollection = integercollection; 6

A Simple Example Collection<String> stringcollection = Collection<Integer> integercollection = stringcollection.add("hello"); integercollection.add(5); integercollection.add(new Integer(6)); stringcollection.add(7); integercollection.add("world"); stringcollection = integercollection; 7

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

The Iterator Interface Provide a way to access the elements of a collection sequentially without exposing the 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! 9

Iterating over a Collection Explicitly using an Iterator for (Iterator<String> iter = stringcollection.iterator(); iter.hasnext(); ) { System.out.println(iter.next()); } Using foreach synatx for (String str : stringcollection) { System.out.println(str); } 10

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

General Purpose Implementations No Direct Implementation <<interface>> Collection <<interface>> Map <<interface>> Set <<interface>> List <<interface>> Queue <<interface>> SortedMap <<interface>> SortedSet HashSet TreeSet ArrayList LinkedList HashMap TreeMap 12

Interface List Example List<Integer> list = new ArrayList<Integer>(); list.add(3); list.add(1); list.add(new Integer(1)); list.add(new Integer(6)); list.remove(list.size()-1); System.out.println(list); Implementation List holds Integer 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); set.add(1); set.add(new Integer(1)); set.add(new Integer(6)); set.remove(6); System.out.println(set); A set does not allow duplicates. It does not contain: two references to the same object two references to null references to two objects a and b such that a.equals(b) Output: [1, 3] or [3, 1] remove() can get only reference as argument Insertion order is not guaranteed (unlike LinkedHashSet) 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 at the end 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"); map.put("leo", "08-5530098"); map.put("rita", "06-8201124"); System.out.println(map); Output: No key duplicates Unordered {Leo=08-5530098, Dan=03-9516743, Rita=06-8201124} Keys (names) Values (phone numbers) Dan 03-9516743 Rita 09-5076452 06-8201124 Leo 08-5530098 16

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

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"); System.out.println(map); lexicographic order Output: {Dan=03-9516743, Leo=08-5530098, Rita=06-8201124} Keys (names) Values (phone numbers) Dan 03-9516743 Leo 08-5530098 Rita 06-8201124 18

Map Collection Views Three views of a Map<K,V> as a collection keyset values entryset Set<K> Collection<V> Set<Map.Entry<K,V>> The Set of key-value pairs (implement Map.Entry) 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 (Map.Entry<String,String> entry: map.entryset()) { System.out.println(entry.getKey() + ": " + entry.getvalue()); } Output: Leo: 08-5530098 Dan: 03-9516743 Rita: 06-8201124 21

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

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

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 other); } Returns a negative value if this < other zero if this.equals(other) a positive value if this > other Error when sorting a list whose elements - do not implement Comparable or - are not mutually comparable. User defined comparator Collections.sort(List, Comparator); 24

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

Diamond Notation Since java 7.0: Set<String> s = new HashSet<String>(); Set<String> s = new HashSet<>(); No need to specify the generic type in a new statement Map<String, List<String>> mymap = new HashMap<String, List<String>>(); Map<String, List<String>> mymap = new HashMap<>(); Not the same as: Map<String, List<String>> mymap = new HashMap(); (Compilation warning) 26