תוכנה 1 תרגול 8 – מבני נתונים גנריים. 2 Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 5 The Collections API.
Advertisements

Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
JAVA Programming (Session 7) When you are willing to make sacrifices for a great cause, you will never be alone. Instructor:
Collections Framework A very brief look at Java’s Collection Framework David Davenport May 2010.
1 L43 Collections (3). 2 OBJECTIVES  To use the collections framework interfaces to program with collections polymorphically.  To use iterators to “walk.
15-Jun-15 Lists in Java Part of the Collections Framework.
Algorithm Programming Containers in Java Bar-Ilan University תשס " ו by Moshe Fresko.
Java Collection Framework. Interface Collection add(o) Add a new element clear() Remove all elements contains(o) Membership checking. IsEmpty() Whether.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Collections A First Glimpse. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector is a kind of collection.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L15 (Chapter 22) Java Collections.
Lists in Java Part of the Collections Framework. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection.
12-Jul-15 Lists in Java Part of the Collections Framework.
The Collections Framework A Brief Introduction. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector.
Chapter 10 2D Arrays Collection Classes. Topics Arrays with more than one dimension Java Collections API ArrayList Map.
Chapter 19 Java Data Structures
Java Collections. Collections, Iterators, Algorithms CollectionsIteratorsAlgorithms.
Java's Collection Framework
Java Collections Framework A presentation by Eric Fabricant.
CS Collection and Input/Output Classes CS 3331 Fall 2009.
Sets and Maps Part of the Collections Framework. The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities.
Advanced Java Session 3 New York University School of Continuing and Professional Studies.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Collections F The limitations of arrays F Java Collection Framework hierarchy  Use the Iterator interface to traverse a collection  Set interface, HashSet,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
1 Java's Collection Framework By Rick Mercer with help from The Java Tutorial, The Collections Trail, by Joshua BlockThe Collections Trail.
(c) University of Washington14-1 CSC 143 Java Collections.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Sets Recall from chapter 22 that one of the Collection subclasses is the Set – A Set is a list in which there are no duplicate entries, which you might.
111 © 2002, Cisco Systems, Inc. All rights reserved.
COLLECTIONS Byju Veedu s/Collection.html.
Object Oriented Programming Ders 10: Data Structures Mustafa Emre İlal
Chapter 18 Java Collections Framework
1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
Computer Science 209 Software Development Java Collections.
Collections –data structures and Algorithms L. Grewe.
Data structures and algorithms in the collection framework 1.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
Arrays, ArrayLists, and Collections. Rationale Suppose we have a program to compute the average of three numbers. We could write a simple little method.
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Generics and Collections Course Lecture Slides 19 th July 2010 “Never.
1 Collections Framework A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain:
16-August-2002cse Libraries © 2002 University of Washington1 Class Libraries CSE 142, Summer 2002 Computer Programming 1
1 Interfaces in Java’s Collection Framework Rick Mercer.
Collections Data structures in Java. OBJECTIVE “ WHEN TO USE WHICH DATA STRUCTURE ” D e b u g.
SETS AND MAPS Collections of Data. Advanced Data Structures Often referred to as the Java Collections Framework…. Set and map data types Hash tables Binary.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
Priority Queues. Priority Queue ADT A priority queue stores a collection of entries Each entry is a pair (key, value) Main methods of the Priority Queue.
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
1 Java's Collection Framework Map and Sets. 2 Collection Framework  A collections framework is a unified architecture for representing and manipulating.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
AD Lecture #3 Java Collection Framework 1.
University of Limerick1 Collections The Collection Framework.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 21 Sets and Maps.
4-Mar-16 Introduction to Collections. Revision questions True false questions 0 for False 1 for True Please do not answer anything other than the above.
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
CS202 Java Object Oriented Programming Introduction to Collection Classes Chengyu Sun California State University, Los Angeles.
Introduction to Java Collection. Java Collections What are they? –A number of pre-packaged implementations of common ‘container’ classes, such as LinkedLists,
©Karsten Lundqvist Example: Array and Arrays 1 import java.util.*; public class Example { private int intValues[] = { 1, 2, 3, 4, 5, 6 }; private double.
Java Collections CHAPTER 3-February-2003
תרגול 7 – מבני נתונים גנריים רובי בוים ומתי שמרת
Chapter 19 Java Data Structures
Java Collections Overview
Containers and Iterators
Introduction to Java Collection
Presentation transcript:

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

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

3 Online Resources Java 6 API Specification: The Collections framework in java.utiljava.util Sun Tutorial:

4 Collection Interfaces > Map > SortedMap > Collection > Set > List > SortedSet Unordered Rejects duplicates Ordered Allows duplicates Ordered Rejects duplicates Ordered Rejects duplicates Unordered Rejects duplicates > Queue FIFO Order Allows duplicates extends

Collection stringCollection = … Collection 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 stringCollection = … Collection 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 של מחרוזות ושל מספרים Collection אינו מחזיק טיפוסים פרימיטיביים, לכן נשתמש ב Integer, Double, Float וכדומה נראה בהמשך אילו מחלקות מממשות מנשק זה

Collection stringCollection = … Collection integerCollection = … stringCollection.add("Hello");  integerCollection.add(5);  integerCollection.add(new Integer(6));  stringCollection.add(7);  integerCollection.add(“world”);  stringCollection = integerCollection;  7 A Simple Example

8 Collection extends Iterable > Collection > Set > List > SortedSet > Queue > Iterable has only one method: IteratorIterator iterator();iterator

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

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

11 Collection Implementations Class Name Convention: Data Structures General Purpose Implementations Linked List Balanced Tree Resizable Array Hash Table TreeSet (SortedSet) HashSet Set Interfaces LinkedListArrayDeque Queue LinkedListArrayList List TreeMap (SortedMap) HashMap Map

12 > Collection > Set > List > SortedSet HashSetTreeSet No Direct Implementation LinkedListArrayList General Purpose Implementations > Map > SortedMap HashMap TreeMap > Queue

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

14 Set set = new HashSet (); set.add(3); set.add(1); set.add(new Integer(1)); set.add(new Integer(6)); set.remove(6); System.out.println(set); Set Example Output: [1, 3] or [3, 1] 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) remove() can get only reference as argument Insertion order is not guaranteed

15 Queue 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); Queue Example Output: [1, 1, 6] FIFO order remove() may have no argument – head is removed Elements are added at the end of the queue

16 Map map = new HashMap (); map.put("Dan", " "); map.put("Rita", " "); map.put("Leo", " "); map.put("Rita", " "); System.out.println(map); Output: {Leo= , Dan= , Rita= } Map Example Keys (names)Values (phone numbers) Dan Rita Leo No duplicates Unordered

17 SortedMap map = new TreeMap (); map.put("Dan", " "); map.put("Rita", " "); map.put("Leo", " "); map.put("Rita", " "); System.out.println(map); Output: {Dan= , Leo= , Rita= } SortedMap Example lexicographic order Keys (names)Values (phone numbers) Dan Rita Leo

18 Map Collection Views Three views of a Map as a collection keySetvaluesentrySet Set Collection Set > The Set of key-value pairs (implement Map.Entry )

19 Iterating Over the Keys of a Map Map map = new HashMap (); map.put("Dan", " "); map.put("Rita", " "); map.put("Leo", " "); map.put("Rita", " "); for (Iterator iter= map.keySet().iterator(); iter.hasNext(); ) { System.out.println(iter.next()); } Output: Leo Dan Rita

20 Iterating Over the Keys of a Map Map map = new HashMap (); map.put("Dan", " "); map.put("Rita", " "); map.put("Leo", " "); map.put("Rita", " "); for (String key : map.keySet()) { System.out.println(key); } Output: Leo Dan Rita

21 Iterating Over the Key-Value Pairs of a Map Map map = new HashMap (); map.put("Dan", " "); map.put("Rita", " "); map.put("Leo", " "); map.put("Rita", " "); for (Iterator > iter= map.entrySet().iterator(); iter.hasNext(); ) { Map.Entry entry = iter.next(); System.out.println(entry.getKey() + ": " + entry.getValue()); } Output: Leo: Dan: Rita:

22 Iterating Over the Key-Value Pairs of a Map Map map = new HashMap (); map.put("Dan", " "); map.put("Rita", " "); map.put("Leo", " "); map.put("Rita", " "); for (Map.Entry entry: map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } Output: Leo: Dan: Rita:

23 Collection Algorithms Defined in the Collections classCollections Main algorithms: sort binarySearch reverse shuffle min max

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

25 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 : public interface Comparable { public int compareTo(T o); } Error when sorting a list whose elements - do not implement Comparable or - are not mutually comparable. User defined comparator Collections.sort(List, Comparator);

26 Best Practice Specify an element type only when a collection is instantiated: Set s = new HashSet (); public void foo(HashSet s){…} public void foo(Set s) {…} s.add() invokes HashSet.add() Works, but… Better! polymorphism Interface Implementation