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

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

Object-Oriented Programming with Java

DM550 Introduction to Programming part 2. Jan Baumbach.

DM550 Introduction to Programming part 2. Jan Baumbach.

Generics Collection Framework

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

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

Java Collections Framework. 24 April 2013 OSU CSE 1

CMSC 202H. Containers and Iterators

PIC 20A Collections and Data Structures

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

Java Collections Framework

Java Magistère BFA

Topic 10: The Java Collections Framework (and Iterators)

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

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

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

CONTAİNERS COLLECTİONS

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

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

An Interface with Generics

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

Collections (Java) Collections Framework

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

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

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

Java Collections Framework reloaded

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Class 32: The 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.

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

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

Computational Applications in Nuclear Astrophysics using Java Java course Lecture 6

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

Programming Languages and Techniques (CIS120)

Advanced Programming Generics Collections

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

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

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

Collections Framework: Part 2

Frameworks. CS151 Chris Pollett Oct. 26, 2005.

Fundamental language mechanisms

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-

USAL1J: Java Collections. S. Rosmorduc

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

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

Computer Science II (Spring )

CHAPTER 7 GENERICS, COLLECTIONS, AND ALGORITHMS

CS11 Java. Winter Lecture 8

Programming Languages and Techniques (CIS120)

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

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

EXAMINATIONS 2016 TRIMESTER 2

Sets and Maps. Part of the Collections Framework

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

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

Collections and Maps

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

Model Solutions. COMP 103: Test April, 2013

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

CSE 143X. Accelerated Computer Programming I/II

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

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

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

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

Java Collections. Wrapper classes. Wrapper classes

Java Collections. Engi Hafez Seliem

Collections Questions

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

Practical Session 3 Java Collections

Binghamton University. CS-140 Fall Interfaces

Generics and collections

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

Generic Collections CSC Spring 2019 Howard Rosenthal

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

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

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

Algorithms. Produced by. Eamonn de Leastar

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.

EXAMINATIONS 2017 TRIMESTER 2

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

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

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

Binghamton University. CS-140 Fall Interfaces

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

Collections. James Brucker

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

First Name Last Name ID#

CSC 1214: Object-Oriented Programming

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

Tony Valderrama, SIPB IAP 2010

CONTAINS SOLUTIONS!!!

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

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/8/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)); stringcollection.add(7); integercollection.add("world"); stringcollection = integercollection;

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)); stringcollection.add(7); integercollection.add("world"); stringcollection = integercollection;

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

10 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); }

11 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

12 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

13 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

14 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)

15 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

16 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

17 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

18 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

19 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)

20 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

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

24 Sorting and Comparing 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 the interface 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);

25 Comparable and Comparator Example Write the class Point that represents a point in the plane How to sort List<Point>? By the x value? By the y value? Distance from the origin?... 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.html

26 Implementing Comparable public class Point implements Comparable<Point>{ } public int compareto(point other) { //comparison by the x axis return this.x - other.x; } The program: 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)] Alternatively: Integer.compare( this.x, other.x);

27 Writing a Comparator public class YAxisPointComparator implements Comparator<Point> { public int compare(point p1, Point p2) { return p1.gety() - p2.gety(); } } The program: 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) Comparing by the Y axis

28 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

29 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