05 - Containers. 2 -------------- DRAFT COPY ------------------------ © S. Uchitel, 2004 Container OrderedDuplicates BagsNOYES SetsNONO ListsYESYES MapsNO.

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

JAVA Programming (Session 7) When you are willing to make sacrifices for a great cause, you will never be alone. Instructor:
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
Java Collections Framework COMP53 Oct 24, Collections Framework A unified architecture for representing and manipulating collections Allows collections.
15-Jun-15 Lists in Java Part of the Collections Framework.
Algorithm Programming Containers in Java Bar-Ilan University תשס " ו by Moshe Fresko.
What Is a Collection?  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
1 The Collection Interface public interface Collection extends Iterable { boolean add(E e); boolean addAll(Collection c); void clear(); boolean contains(Object.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L15 (Chapter 22) Java Collections.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 17 Advanced Java Concepts Data Structure Support.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
Collections The objectives of this chapter are: To outline the Collections infrastructure in Java To describe the various collection classes To discuss.
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.
1 Frameworks Part 2. 2 Collections Framework Java API contains library of useful data structures Collections library also serves as framework for adding.
Chapter 19 Java Data Structures
Java's Collection Framework
Collections. Why collections? Collections are used to hold a collection of objects. List holds objects based on order of insertion and can hold non unique.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections 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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
(c) University of Washington14-1 CSC 143 Java Collections.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Chapter 18 Java Collections Framework
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Data structures and algorithms in the collection framework 1.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
1.0tCopyright © 1998 Purple Technology, Inc. 1 Java Collections Framework Authored by Alex Chaffee Copyright © 1998 Purple Technology, Inc. All rights.
Sets and Maps Chris Nevison. Set Interface Models collection with no repetitions subinterface of Collection –has all collection methods has a subinterface.
The Java Collections Framework Based on
CSC 142 P 1 CSC 142 Collections [Reading: Chapter 10]
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
Java 2 Collections Bartosz Walter Software Engineering II.
1 Collections Framework A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain:
Sadegh Aliakbary Sharif University of Technology Fall 2012.
1 Interfaces in Java’s Collection Framework Rick Mercer.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
© 2006 Pearson Addison-Wesley. All rights reserved5 B-1 Chapter 5 (continued) Linked Lists.
CS Ananda Gunawardena.  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
Copyright (c) Systems and Computer Engineering, Carleton University * Object-Oriented Software Development Unit 13 The Collections Framework.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
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.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
1/20/05A-1 © 2001 T. Horton CS 494 Adv. SW Design and Development A Tasting…. Course 1: Design patterns: Intro, example Course 2: Inheritance, Interfaces,
Data Structures I Collection, List, ArrayList, LinkedList, Iterator, ListNode.
1 Copyright © 2011 Tata Consultancy Services Limited COLLECTIONS By TEAM 5 Rajendhiran Sivan Christi Yashwanth Bijay Smruthi Satyajit.
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.
Collections Dwight Deugo Nesa Matic
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
 2016, Marcus Biel, ArrayList Marcus Biel, Software Craftsman
CS 151: Object-Oriented Design December 3 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Data Structures Lakshmish Ramaswamy.
Introduction to Collections
Introduction to Collections
Introduction to Collections
Part of the Collections Framework
Collections in Java The objectives of this lecture are:
Introduction to Collections
Collections Framework
Introduction to Collections
Hashing in java.util
Part of the Collections Framework
Java Generics & Iterators
Presentation transcript:

05 - Containers

DRAFT COPY © S. Uchitel, 2004 Container OrderedDuplicates BagsNOYES SetsNONO ListsYESYES MapsNO key value pairs key unique for each element Bags are not included in the Java Standard Library. Bags are not included in the Java Standard Library. A container allows objects to be stored and retrieved. A container allows objects to be stored and retrieved. There are different types of collections according to the additional services and behaviour they implement There are different types of collections according to the additional services and behaviour they implement

DRAFT COPY © S. Uchitel, 2004 The Container Class Hierarchy class HashSet extends AbstractSet implements Set … { … } Extract from the Java Standard Library hierarchy for Containers interface Map Vector

DRAFT COPY © S. Uchitel, 2004 java.util.Collection > interface Collection { // This is only a subset of the methods boolean add(Object o) ; boolean remove(Object o); boolean contains(Object o); // How do you think this is implemented? boolean isEmpty(); Iterator iterator(); // Returns an iterator over the elements // Returns an iterator over the elements int size();// Returns the number of elements // … many other methods } Refer to the Java Documentation for the full definition!

DRAFT COPY © S. Uchitel, 2004 What is an Iterator? Iterator – An interface which permits iteration over the elements of a collection: Iterator – An interface which permits iteration over the elements of a collection: interface Iterator { // This is only a subset of the methods boolean hasNext(Object o); Object next() ; boolean remove(Object o); // … many other methods }

DRAFT COPY © S. Uchitel, 2004 Collections and Iterators: Examples public printStudents(Collection students) { Iterator myIterator = students.iterator(); while (myIterator.hasNext()) { Student s = (Student) myIterator.next(); System.out.println(s.name);} public findAndPrintName(Collection c, String login) { Iterator myIterator = c.iterator(); while (myIterator.hasNext()) { Student s = (Student) myIterator.next(); if (s.getLogin().equals(login)) System.out.println(s.name); System.out.println(s.name); // Once found I continue to search. I do not // Once found I continue to search. I do not // assume the collection is a set. // assume the collection is a set.}} Why is this casting needed? Is it up or down? Are we guaranteed success?

DRAFT COPY © S. Uchitel, 2004 Sets A set is a Collection that cannot contain duplicate elements A set is a Collection that cannot contain duplicate elements Interestingly, the interface set does not add anything to the collection interface. However, it is documented differently (the pre and post conditions of the methods change) Interestingly, the interface set does not add anything to the collection interface. However, it is documented differently (the pre and post conditions of the methods change) Elements compared with equals(Object o). Elements compared with equals(Object o). See the Java documentation for interface Set See the Java documentation for interface Set

DRAFT COPY © S. Uchitel, 2004 Sets: Example public Set getUndergraduateStudents(Set students) { // Returns a set with all undergraduates // that are in set students. Set undergrads = new HashSet(); //Why not “new Set();”? Iterator myIterator = students.iterator(); while (myIterator.hasNext()) { Object o = myIterator.next(); if (o.instanceOf(Undergraduate)) undergrads.add(o); undergrads.add(o);} return undergrads; } Note that the actual type returned (HashSet) is a subclass of the return type declared (Set) Decouples method user from our choice implementation for the set of undergraduates Note that parameter type Set decouples us from the method user’s choice of implementation for the set of students

DRAFT COPY © S. Uchitel, 2004 Sets and Equality: Example public class Book { protected int isdn; protected int isdn; protected String title; protected String title; Book(int isdn, String title) { Book(int isdn, String title) { this.isdn = isdn; this.isdn = isdn; this.title = title this.title = title } public boolean equals(Book b) { public boolean equals(Book b) { return (isdn == b.isdn) return (isdn == b.isdn) }} public void example() { Set s = new HashSet(); Set s = new HashSet(); Book b = new Book(1, “Kenya”); Book b = new Book(1, “Kenya”); s.add(); s.add(); //s.size() is 1 //s.size() is 1 s.add(new Book(2, “Haskell”)); s.add(new Book(2, “Haskell”)); //s.size() is 2 //s.size() is 2 s.add(new Book(1, “Java”)); s.add(new Book(1, “Java”)); //s.size() is 2 //s.size() is 2 s.add(new Book(3, “Haskell”)); s.add(new Book(3, “Haskell”)); //s.size() is 3 //s.size() is 3 s.remove(b); s.remove(b); //s.size() is 2 //s.size() is 2 s.add(new Book(1, “Java”)); s.add(new Book(1, “Java”)); //s.size() is 3 //s.size() is 3}

DRAFT COPY © S. Uchitel, 2004 Sorted Sets Some Collections are sorted Some Collections are sorted  see SortedSet Interface (includes first(), last() and others)  see the TreeSet implementations To sort the elements of a collection one needs to either: To sort the elements of a collection one needs to either:  have "Comparable" elements, or  provide a "Comparator" function to the sorted collection upon creation. Comparable elements implement: Comparable elements implement: public interface Comparable { public int compareTo(Object o);/* returns > 0 if this greater than o, 0 if equal or 0 if this greater than o, 0 if equal or < 0 if this less than o */ }// NB. Must be consistent with equals()

DRAFT COPY © S. Uchitel, 2004 Ordered Sets: Example public class Book implements Comparable { protected int isdn; protected int isdn; protected String title; protected String title; Book(int isdn, String title) {...} Book(int isdn, String title) {...} public boolean equals(Book b) {...} public boolean equals(Book b) {...} public void print() { public void print() { System.out.print(isdn + “:” + title); System.out.print(isdn + “:” + title); } public int compareTo(Object o); public int compareTo(Object o); if (o.instanceOf(Book) if (o.instanceOf(Book) return (isdn–((Book) o).isdn)); return (isdn–((Book) o).isdn)); else else return –1; return –1; }}} public void easySort(Set books) { SortedSet s = new TreeSet(); SortedSet s = new TreeSet(); s.addAll(books); s.addAll(books); myIt = s.iterator(); myIt = s.iterator(); while (myIt.hasNext()) { while (myIt.hasNext()) { Book b = (Book) myIt.next(); Book b = (Book) myIt.next(); b.print(); b.print(); }}

DRAFT COPY © S. Uchitel, 2004 Lists Ordered collection which may contain duplicate elements Ordered collection which may contain duplicate elements Provide operations for Provide operations for  Positional access – manipulate elements based on their numerical position in the list  Search  Extended iterator

DRAFT COPY © S. Uchitel, 2004 Lists

DRAFT COPY © S. Uchitel, 2004 List > public interface List extends Collection { void add(int index, Object o); Object get(int index); // Returns the element at index int indexOf(Object o); /* Returns the index in this list of the first occurrence of the specified element, or -1 if this list does not contain this element */ int lastIndexOf(Object o) ; ListIterator listIterator() ;// Returns a list iterator - guaranteed order ListIterator listIterator(int index) ; Object remove(int index) ; Object set(int index, Object element); // replace element at index List subList(int fromIndex, int toIndex) ;// returns sublist between indexes // … }

DRAFT COPY © S. Uchitel, 2004 ListIterator > public interface ListIterator extends Iterator { void add(Object o) ; boolean hasPrevious() ; int nextIndex() ;// Returns the index of the next element Object previous() ; int previousIndex() ;// Returns the index of the previous element void set(Object o); // Replaces the element at the current index } Index What do alternate calls to next and previous return?

DRAFT COPY © S. Uchitel, 2004 List: Example // Swap two elements with index i and j in a list public static void swap(List l, int i, int j) { Object tmp = l.get(i); l.set(i, l.get(j)); l.set(j, tmp); } // Sort elements on add. Requires elements to implement Comparable class MySortedSet { private LinkedList _obj = new LinkedList(); public boolean add(Object o) { Comparable c = (Comparable) o; // run time error if this fails ListIterator i = _obj.listIterator(); while (i.hasNext()) { int val = c.compareTo(i.next()); if (val == 0) { return false; /* Object already exists*/ } if (val < 0) {_obj.add(i.previousIndex(),o); return true; } } _obj.addLast(o); return true; }}

DRAFT COPY © S. Uchitel, 2004 Maps Stores pairs of objects: Stores pairs of objects: They are not a subclass of Container They are not a subclass of Container Map Interface: Map Interface:  void put(Object key, Object value)  Object get(Object key)  Set keySet() <- Keys are unique  Collection values() <- A value could be paired to several keys Careful: if you modify the object returned by keySet() or values() you are tinkering with the internal representation of the map! Careful: if you modify the object returned by keySet() or values() you are tinkering with the internal representation of the map!

DRAFT COPY © S. Uchitel, 2004 Maps: Example public class Registrations { Map regs = new HashMap(); Map regs = new HashMap();... public register(Student s, Course c) { public register(Student s, Course c) { Set mySet; Set mySet; if (!regs.keySet().contains(c)) { if (!regs.keySet().contains(c)) { //Map has no set of registered students for course c //Map has no set of registered students for course c mySet = new HashSet(); mySet = new HashSet(); regs.put(c, mySet); //Associate empty set to course c regs.put(c, mySet); //Associate empty set to course c } else {//Get set of students registered for c else {//Get set of students registered for c mySet = (Set) regs.get(c); mySet = (Set) regs.get(c); } //mySet is the set of registered students for course c mySet.add(s); //Add student to set of registered students for c mySet.add(s); //Add student to set of registered students for c} Note that there is no need to do regs.put(c, mySet) to update the map. Why?

DRAFT COPY © S. Uchitel, 2004 Summary Implementations Hash Table Resizable Array Balanced Tree Linked List InterfacesSetHashSetTreeSet ListArrayListLinkedList MapHashMapTreeMap

DRAFT COPY © S. Uchitel, 2004 Checklist Collections Collections Bags vs. Sets vs. Lists vs. Maps Bags vs. Sets vs. Lists vs. Maps The Java Collections Hierarchy: Interfaces, Abstract Classes and Concrete Classes The Java Collections Hierarchy: Interfaces, Abstract Classes and Concrete Classes Iterators Iterators Sets and equality Sets and equality Sorted sets and the Comparable interface Sorted sets and the Comparable interface Lists and ListIterators Lists and ListIterators Maps Maps