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

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

תוכנה 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

DM550 Introduction to Programming part 2. Jan Baumbach.

DM550 Introduction to Programming part 2. Jan Baumbach.

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

Generics Collection Framework

הנכות 1 םוכיס לוגרת 13 1

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

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

הנכות 1 םוכיס לוגרת 13 1

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

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

CMSC 202H. Containers and Iterators

הנכות 1 םוכיס לוגרת 13 1

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

PIC 20A Collections and Data Structures

Topic 10: The Java Collections Framework (and Iterators)

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

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

Java Collections Framework. 24 April 2013 OSU CSE 1

CONTAİNERS COLLECTİONS

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. CSE 403, Spring 2004 Software Engineering

Java Collections Framework

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

An Interface with Generics

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

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

Java Magistère BFA

Collections and Maps

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

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Collections Framework: Part 2

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

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

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

הנכות 1 םוכיס לוגרת 14 1

Sets and Maps. Part of the Collections Framework

Class 32: The Java Collections Framework

Generics and collections

EXAMINATIONS 2016 TRIMESTER 2

Model Solutions. COMP 103: Test April, 2013

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.

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

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

Java Collections Framework reloaded

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

לתיכנות עם MATLAB Lecture 5: Boolean logic and Boolean expressions

Practical Session 3 Java Collections

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

Collections (Java) Collections Framework

מבוא למדעי המחשב תרגול 8 רשימה משורשרת כללית, Comparator

Fall 2017 Mentoring 7: October 9, Abstract Data Types

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

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

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

Algorithms. Intro2CS week 5

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

CS11 Java. Winter Lecture 8

תוכנה 1 סמסטר א' תשע"א

Programming Languages and Techniques (CIS120)

EXAMINATIONS 2017 TRIMESTER 2

Algorithms. Produced by. Eamonn de Leastar

Programming Languages and Techniques (CIS120)

Advanced Programming Generics Collections

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

Java Collections. Wrapper classes. Wrapper classes

Java Collections. Engi Hafez Seliem

USAL1J: Java Collections. S. Rosmorduc

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

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

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

לתיכנות עם MATLAB Lecture 5: Boolean logic and Boolean expressions

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

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 Collection Framework

CSE 143X. Accelerated Computer Programming I/II

Charlie Garrod Bogdan Vasilescu

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

Agenda. Inner classes and implementation of ArrayList Nested classes and inner classes The AbstractCollection class Implementation of ArrayList

CSE 143. Computer Programming II

תוכנה 1 בשפת Java נושאים שונים בהורשה רובי בוים ומתי שמרת בית הספר למדעי המחשב אוניברסיטת תל אביב

Collections and Iterators. Collections

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

What is the Java Collections Framework?

Computational Applications in Nuclear Astrophysics using Java Java course Lecture 6

Computer Science II (Spring )

CSC 321: Data Structures. Fall 2016

CSC 321: Data Structures. Fall 2017

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 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

Fundamental language mechanisms

JAVA COLLECTION FRAMEWORK & SETS

CHAPTER 7 GENERICS, COLLECTIONS, AND ALGORITHMS

Java Collections Framework: Interfaces

Transcription:

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

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

3 Online Resources Java 7 API Specification of the Collections Framework: https://docs.oracle.com/javase/7/docs/technotes/guides /collections/reference.html Oracle Tutorial: http://docs.oracle.com/javase/tutorial/collections/

4 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

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

6 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));

7 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;

8 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>

9 המנשק Iterator מספק דרך לגשת לאיברים של אוסף המימוש שלו. שירותים: hasnext() מחזיר true next() )collection( מבלי לחשוף את אם יש עוד איברים שלא עברנו עליהם באוסף, false מחזיר את האיבר הבא באוסף גם שאילתא וגם פעולה, זאת כיוון ש next remove() מוחק את האיבר האחרון שהוחזר על ידי האיטרטור. זו מקדם את האיטרטור. מתודה אופציונלית. אם לא ממומשת תיזרק שגיאת זמן ריצה מסוג.UnsupportedOperationException אחרת.

10 Iterating over a Collection שימוש מפורש באיטרטור: for (Iterator<String> iter = stringcollection.iterator(); iter.hasnext(); ) { System.out.println(iter.next()); לולאת :while while (iter.hasnext()){ שימוש ב foreach for (String str : stringcollection) { System.out.println(str);

11 Deleting an item inside a loop for (String str : stringcollection) { שימוש ב foreach עלול לגרום לשגיאה בעדכון האוסף if (somecondition){ stringcollection.remove(str); //can possible cause ConcurrentModificationException שימוש ב iterator הוא בטוח יותר for (Iterator<String> iter = stringcollection.iterator(); iter.hasnext(); ) { iter.next(); /*we must advance the iterator, otherwise we will get IllegalStateException */ if (somecondition){ iter.remove(); /*this is safe, unless remove is not supported*/

12 Incorrect usage of iterators מה לא בסדר בקוד הבא? public static int getfirstnegativenuminlist(list<integer> lst){ Integer item = null; while (item > 0){ Iterator<Integer>it = lst.iterator(); item = it.next(); return item; בכל איטרציה נקבל איטרטור שמתחיל מתחילת הרשימה, כך שלמעשה אנחנו בודקים את אותו האיבר בכל איטרציה אם האיבר הראשון ב lst הוא שלילי, הפונקציה תסתיים אחרי איטרציה אחת ותחזיר את האיבר הנכון. אחרת לולאה אינסופית.

13 General Purpose 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

14 Adding Implementations to the Picture No Direct Implementation <<interface>> Collection <<interface>> Map <<interface>> Set <<interface>> List <<interface>> Queue <<interface>> SortedMap <<interface>> SortedSet HashSet TreeSet ArrayList LinkedList HashMap TreeMap

15 Collection interface מתודות שימושיות במנשק :Collection<E> description ensures that this collection contains the specified element (optional operation) Removes a single instance of the specified element from this collection, if it is present (optional operation). method name Boolean add(e e) boolean remove(object o) removes all elements in the Collection void clear() returns true if this collection contains the specified element boolean contains(object o) returns true if this collection contains no elements returns the number of elements in this collection. returns an iterator over the elements in this collection. boolean int Iterator<E> isempty() size() iterator() רשימת המתודות המלאה: http://docs.oracle.com/javase/7/docs/api/java/util/collection.html

16 description Map interface associates the specified value with the specified key in this map (optional operation) removes the mapping for a key from this map if it is present (optional operation). removes all of the mappings from this map (optional operation). returns true if this map contains a mapping for the specified key returns true if this collection contains no elements : מתודות שימושיות במנשק Map<K,V> boolean method name put(k key, V value) boolean remove(object o) void boolean key) boolean clear() containskey(object isempty() returns the number of key-value mappings in this map. returns a set view of the keys contained in this map int Set<K> size() keyset() returns a Collection view of the values contained in this map. Collection<V> values() רשימת המתודות המלאה: http://docs.oracle.com/javase/7/docs/api/java/util/map.html

17 מבוצע auto-boxing אובייקטים מטיפוס List Example מנשק List<Integer> list = new ArrayList<Integer>(); list.add(3); מימוש list.add(1); כך שנשמרים Integer(1)); list.add(new list.add(new Integer(6)); Integer list.remove(list.size()-1); System.out.println(list); ניתן להעביר ל remove את האינדקס של האובייקט שאנו רוצים למחוק, או המצביע אליו. Output: [3, 1, 1] שימוש במתודה.ArrayList של tostring סדר האיברים הוא לפי סדר הכנסתם לרשימה

18 Set Example Set<Integer> set = new HashSet<Integer>(); set.add(3); set.add(1); set.add(new Integer(1)); )בפרט set.add(new Integer(6)); x ו y מצביעים לאותו set.remove(6); System.out.println(set); Output: [1, 3] or [3, 1] Set שני איברים אינו מאפשר איברים כפולים. x ו y יחשבו לאיברים כפולים אם: 1. שניהם הם null x.equals(y) == true.2 מתקיים כאשר האובייקט(. remove() יכול לקבל רק אובייקט, כיוון שאין משמעות לאינדקס באוסף שלא שומר על סדר השתמשו ב ב TreeSet או ב LinkedHashSet ע"מ להבטיח סדר

19 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: {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

20 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 מסודר לפי סדר הכנסת המפתחות )הפעם הראשונה שבה מפתח מוכנס ) Keys (names) Values (phone numbers) Dan 03-9516743 Rita 06-8201124 Leo 08-5530098

21 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); Output: {Dan=03-9516743, Leo=08-5530098, Rita=06-8201124 סדר לקסיקוגרפי של המפתחות Keys (names) Values (phone numbers) Dan 03-9516743 Leo 08-5530098 Rita 06-8201124

22 Map Collection Views A Map is not Iterable! 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)

23 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

24 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"); מחזיר אובייקט מטיפוס Set<Map.Entry<K,V>> המכיל את כל המיפויים במילון. 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

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

26 Sorting 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 the array Arguments: A C D B Output: [A, B, C, D]

27 How can we sort a list of objects? 1. Collections.sort(myList) mylist s elements implement Comparable<T> interface. public interface Comparable<T> { /********************************** * $ret < 0 if this < other * * $ret = 0 if this.equals(other) * * $ret > 0 if this > other * **********************************/ public int compareto(t other); Error when sorting a list whose elements - do not implement Comparable or - are not mutually comparable. String implements the interface Comparable<String> so we are able to sort a list of strings.

28 How can we sort a list of objects? 1. Collections.sort(myList, mycomparator) mycomparator implement Comparator<T> interface. public interface Comparator<T>{ /********************************** * $ret < 0 if o1 < o2 * * $ret = 0 if o1.equals(o2) * * $ret > 0 if o1 > o2 * **********************************/ public int compare(t o1, T o2); The comparator interface enables us to sort a list of the same object by different critiria, using different comparators.

29 Comparable and Comparator Example Write the class Point that represents a point in the plane How to sort List<Point>? Two options: public class Point { private int x; private int y;... Make Point implement Comparable<Point>, and use Collections.sort Write a class that implements Comparator<Point>, and pass it as an argument to Collections.sort. Don t: write a sorting algorithm yourselves! Recommended Tutorial: http://docs.oracle.com/javase/tutorial/collections/interfaces/order.h tml

30 The program: Implementing Comparable public class Point implements Comparable<Point>{ public int compareto(point other) { //comparison by the x axis Integer.compare(this.x, other.x); //also possible: return this.x - other.x; List<Point> pointlist = new LinkedList<Point>(); pointlist.add(new Point(1, 3)); pointlist.add(new Point(0, 6)); Collections.sort(pointList); System.out.println(pointList); Output: [(0,6), (1,3)]

31 The program: Writing a Comparator public class YAxisPointComparator implements Comparator<Point> { public int compare(point p1, Point p2) { //comparison by the y axis return Integer.compare(p1.getY(), p2.gety()); //also possible: return p1.gety() p2.get(x); List<Point> pointlist = new LinkedList<Point>(); pointlist.add(new Point(1, 3)); pointlist.add(new Point(0, 6)); Collections.sort(pointList, new YAxisPointComparator()); System.out.println(pointList); The output: [(1,3), (0,6)] Useful for sorting existing classes (e.g., String)

32 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

33 Diamond Notation Set<String> s = new HashSet<String>(); Set<String> s = new HashSet<>(); 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) No need to specify the generic type in a new statement

34 מממש גם את המנשק List Queue כאשר remove לא מקבלת ארגומנטים, האיבר שמוסר מהרשימה הוא האיבר הראשון שנכנס )הראשון בתור( Queue Example Queue<Integer> queue = new LinkedList<>(); 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]

35 LinkedHashSet Example Set<Integer> set = new LinkedHashSet<>(); set.add(3); set.add(1); set.add(new Integer(1)); set.add(new Integer(6)); set.remove(6); System.out.println(set); Set אינו מאפשר איברים כפולים. Output: [3, 1] מסודר ע"פ סדר ההכנסה )הכנסה ראשונה של כל אובייקט(.

36 TreeSet Example Set<Integer> set = new TreeSet<>(); set.add(3); set.add(1); set.add(new Integer(1)); set.add(new Integer(6)); set.remove(6); System.out.println(set); Set אינו מאפשר איברים כפולים. Output: [1, 3] סדר האיברים הוא הסדר ה"טבעי" שלהם. ניתן להעביר Comparator בבנאי ע"מ להשתמש בקריטריון סידור שונה