Java Collections CHAPTER 3-February-2003

Slides:



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

Collections. What is the Collections framework?  Collections framework provides two things: –implementations of common high-level data structures: e.g.
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
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.
Professor Evan Korth (adapted from Sun’s collections documentation)
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.
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.
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.
The Java Collections Package C. DeJong Fall 2001.
Chapter 19 Java Data Structures
Java's Collection Framework
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
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.
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.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Chapter 18 Java Collections Framework
1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
Data structures Abstract data types Java classes for Data structures and ADTs.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
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:
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
CS Ananda Gunawardena.  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
List Interface and Linked List Mrs. Furman March 25, 2010.
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.
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.
University of Limerick1 Collections The Collection Framework.
Collections Dwight Deugo Nesa Matic
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Collections ABCD ABCD Head Node Tail Node array doubly linked list Traditional Arrays and linked list: Below is memory representation of traditional.
Slides by Donald W. Smith
Java Collections OOP tirgul No
Fundamental of Java Programming
Chapter 19 Java Data Structures
Programming & Data Structures
Introduction to Collections
Introduction to Collections
JAVA Collections Framework Set Interfaces & Implementations
Programming in Java Lecture 11: ArrayList
Lecture 6: Collections.
Java语言程序设计 马 皓
Introduction to Collections
Part of the Collections Framework
Collections in Java The objectives of this lecture are:
14.1 The java.util Package.
Introduction to Collections
Collections Framework
Introduction to Collections
Part of the Collections Framework
Presentation transcript:

Java Collections CHAPTER 9 @geoffjuma 3-February-2003 07/14/16 Java Collections CHAPTER 9 @geoffjuma 3-February-2003 Java collection types

07/14/16 Agenda Lists Sets Maps 3-February-2003 Java collection types

Readings and References 07/14/16 Readings and References References "Collections", Java tutorial http://java.sun.com/docs/books/tutorial/collections/index.html 3-February-2003 Java collection types

07/14/16 Java 2 Collections A collection is an object that groups multiple elements into a single unit Very useful store, retrieve and manipulate data transmit data from one method to another data structures and methods written by hotshots in the field 3-February-2003 Java collection types

07/14/16 Problem Example You want to develop a java application for a client in the matatu industry. The matatu carries passengers from a fixed location to a fixed destination but has several stops along the way where passengers can board and alight at will; The matatu can only carry a fixed number of passengers subject to the number of seats available. 3-February-2003 Java collection types

Collections Framework 07/14/16 Collections Framework Unified architecture for representing and manipulating collections. A collections framework contains three things Interfaces Implementations Algorithms 3-February-2003 Java collection types

Collections Framework Diagram 07/14/16 Collections Framework Diagram Interfaces, Implementations, and Algorithms From Thinking in Java, page 462 3-February-2003 Java collection types

Collection Interface Defines fundamental methods 07/14/16 Collection Interface Defines fundamental methods int size(); boolean isEmpty(); boolean contains(Object element); boolean add(Object element); // Optional boolean remove(Object element); // Optional Iterator iterator(); These methods are enough to define the basic behavior of a collection Provides an Iterator to step through the elements in the Collection 3-February-2003 Java collection types

Iterator Interface Defines three fundamental methods 07/14/16 Iterator Interface Defines three fundamental methods Object next() boolean hasNext() void remove() These three methods provide access to the contents of the collection An Iterator knows position within collection Each call to next() “reads” an element from the collection Then you can use it or remove it 3-February-2003 Java collection types

07/14/16 Iterator Position 3-February-2003 Java collection types

Example - SimpleCollection 07/14/16 Example - SimpleCollection public class SimpleCollection { public static void main(String[] args) { Collection c; c = new ArrayList(); System.out.println(c.getClass().getName()); for (int i=1; i <= 10; i++) { c.add(i + " * " + i + " = "+i*i); } Iterator iter = c.iterator(); while (iter.hasNext()) System.out.println(iter.next()); 3-February-2003 Java collection types

List Interface Context 07/14/16 List Interface Context Collection List 3-February-2003 Java collection types

07/14/16 List Interface The List interface adds the notion of order to a collection The user of a list has control over where an element is added in the collection Lists typically allow duplicate elements Provides a ListIterator to step through the elements in the list. 3-February-2003 Java collection types

ListIterator Interface 07/14/16 ListIterator Interface Extends the Iterator interface Defines three fundamental methods void add(Object o) - before current position boolean hasPrevious() Object previous() The addition of these three methods defines the basic behavior of an ordered list A ListIterator knows position within list 3-February-2003 Java collection types

Iterator Position - next(), previous() 07/14/16 Iterator Position - next(), previous() 3-February-2003 Java collection types

ArrayList and LinkedList Context 07/14/16 ArrayList and LinkedList Context Collection List ArrayList LinkedList 3-February-2003 Java collection types

List Implementations ArrayList LinkedList low cost random access 07/14/16 List Implementations ArrayList low cost random access high cost insert and delete array that resizes if need be LinkedList sequential access low cost insert and delete high cost random access 3-February-2003 Java collection types

ArrayList overview Constant time positional access (it’s an array) 07/14/16 ArrayList overview Constant time positional access (it’s an array) One tuning parameter, the initial capacity ArrayList supports dynamic arrays that can grow as needed. Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold. 3-February-2003 Java collection types

07/14/16 ArrayList methods The indexed get and set methods of the List interface are appropriate to use since ArrayLists are backed by an array Object get(int index) Object set(int index, Object element) Indexed add and remove are provided, but can be costly if used frequently void add(int index, Object element) Object remove(int index) May want to resize in one shot if adding many elements void ensureCapacity(int minCapacity) 3-February-2003 Java collection types

07/14/16 ArrayList 3-February-2003 Java collection types

LinkedList overview Stores each element in a node 07/14/16 LinkedList overview Stores each element in a node Each node stores a link to the next and previous nodes Insertion and removal are inexpensive just update the links in the surrounding nodes Linear traversal is inexpensive Random access is expensive Start from beginning or end and traverse each node while counting 3-February-2003 Java collection types

LinkedList entries 3-February-2003 Java collection types 07/14/16 LinkedList entries private static class Entry { Object element; Entry next; Entry previous; Entry(Object element, Entry next, Entry previous) { this.element = element; this.next = next; this.previous = previous; } private Entry header = new Entry(null, null, null); public LinkedList() { header.next = header.previous = header; 3-February-2003 Java collection types

07/14/16 Linked List Example 3-February-2003 Java collection types

LinkedList methods The list is sequential, so access it that way 07/14/16 LinkedList methods The list is sequential, so access it that way ListIterator listIterator() ListIterator knows about position use add() from ListIterator to add at a position use remove() from ListIterator to remove at a position LinkedList knows a few things too void addFirst(Object o), void addLast(Object o) Object getFirst(), Object getLast() Object removeFirst(), Object removeLast() 3-February-2003 Java collection types

Set Interface Context Collection Set 3-February-2003 07/14/16 Set Interface Context Collection Set 3-February-2003 Java collection types

Set Interface Java's java.util.Set interface defines the set. 07/14/16 Set Interface Java's java.util.Set interface defines the set. A set can't have any duplicate elements in it. Additionally, the set has no set order. As such, elements can't be found by index. Same methods as Collection different contract - no duplicate entries Defines two fundamental methods boolean add(Object o) - reject duplicates Iterator iterator() 3-February-2003 Java collection types

Hash Set Hash sets are sets that use hashes to store elements. 07/14/16 Hash Set Hash sets are sets that use hashes to store elements. A hashing algorithm is an algorithm that takes an element and converts it to a chunk of a fixed size called a hash. For example, let our hashing algorithm be (x mod 10). So the hashes of 232, 217 and 19 are 2,7, and 9 respectively 3-February-2003 Java collection types

HashSet Find and add elements very quickly 07/14/16 HashSet Find and add elements very quickly uses hashing implementation in HashMap Hashing uses an array of linked lists The hashCode() is used to index into the array Then equals() is used to determine if element is in the (short) list of elements at that index No order imposed on elements The hashCode() method and the equals() method must be compatible if two objects are equal, they must have the same hashCode() value 3-February-2003 Java collection types

07/14/16 Hash Code 3-February-2003 Java collection types

07/14/16 Buckets 3-February-2003 Java collection types

HashSet and TreeSet Context 07/14/16 HashSet and TreeSet Context Collection Set HashSet TreeSet 3-February-2003 Java collection types

07/14/16 Tree Set TreeSet provides an implementation of the Set interface that uses a tree for storage. Objects are stored in sorted, ascending order. Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly. 3-February-2003 Java collection types

TreeSet Elements can be inserted in any order 07/14/16 TreeSet Elements can be inserted in any order The TreeSet stores them in order Red-Black Trees out of Cormen-Leiserson-Rivest An iterator always presents them in order Default order is defined by natural order objects implement the Comparable interface TreeSet uses compareTo(Object o) to sort Can use a different Comparator provide Comparator to the TreeSet constructor 3-February-2003 Java collection types

Map Interface Context Map 3-February-2003 Java collection types 07/14/16 Map Interface Context Map 3-February-2003 Java collection types

Map Interface Stores key/value pairs Maps from the key to the value 07/14/16 Map Interface Stores key/value pairs Maps from the key to the value Keys are unique a single key only appears once in the Map a key can map to only one value Values do not have to be unique 3-February-2003 Java collection types

Map methods Object put(Object key, Object value) 07/14/16 Map methods Object put(Object key, Object value) Object get(Object key) Object remove(Object key) boolean containsKey(Object key) boolean containsValue(Object value) int size() boolean isEmpty() 3-February-2003 Java collection types

Map views A means of iterating over the keys and values in a Map 07/14/16 Map views A means of iterating over the keys and values in a Map Set keySet() returns the Set of keys contained in the Map Collection values() returns the Collection of values contained in the Map. This Collection is not a Set, as multiple keys can map to the same value. Set entrySet() returns the Set of key-value pairs contained in the Map. The Map interface provides a small nested interface called Map.Entry that is the type of the elements in this Set. 3-February-2003 Java collection types

HashMap and TreeMap Context 07/14/16 HashMap and TreeMap Context Map HashMap TreeMap 3-February-2003 Java collection types

HashMap and TreeMap HashMap TreeMap 07/14/16 HashMap and TreeMap HashMap The keys are a set - unique, unordered Fast TreeMap The keys are a set - unique, ordered Same options for ordering as a TreeSet Natural order (Comparable, compareTo(Object)) Special order (Comparator, compare(Object, Object)) 3-February-2003 Java collection types

07/14/16 Bulk Operations In addition to the basic operations, a Collection may provide “bulk” operations boolean containsAll(Collection c); boolean addAll(Collection c); // Optional boolean removeAll(Collection c); // Optional boolean retainAll(Collection c); // Optional void clear(); // Optional Object[] toArray(); Object[] toArray(Object a[]); 3-February-2003 Java collection types

07/14/16 Utilities Context 3-February-2003 Java collection types

07/14/16 Utilities The Collections class provides a number of static methods for fundamental algorithms Most operate on Lists, some on all Collections Sort, Search, Shuffle Reverse, fill, copy Min, max Wrappers synchronized Collections, Lists, Sets, etc unmodifiable Collections, Lists, Sets, etc 3-February-2003 Java collection types

Legacy classes Still available Don’t use for new development 07/14/16 Legacy classes Still available Don’t use for new development unless you have to, eg, J2ME, J2EE in some cases Retrofitted into Collections framework Hashtable use HashMap Enumeration use Collections and Iterators if needed, can get an Enumeration with Collections.enumeration(Collection c) 3-February-2003 Java collection types

More Legacy classes Vector Stack BitSet Properties use ArrayList 07/14/16 More Legacy classes Vector use ArrayList Stack use LinkedList BitSet use ArrayList of boolean, unless you can’t stand the thought of the wasted space Properties legacies are sometimes hard to walk away from … see next few pages 3-February-2003 Java collection types

Properties class Located in java.util package 07/14/16 Properties class Located in java.util package Special case of Hashtable Keys and values are Strings Tables can be saved to/loaded from file 3-February-2003 Java collection types

07/14/16 System properties Java VM maintains set of properties that define system environment Set when VM is initialized Includes information about current user, VM version, Java environment, and OS configuration Properties prop = System.getProperties(); Enumeration e = prop.propertyNames(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); System.out.println(key + " value is " + prop.getProperty(key)); } 3-February-2003 Java collection types