Lecture 6: Collections.

Slides:



Advertisements
Similar presentations
Introduction to Computation and Problem Solving Class 32: The Java® Collections Framework Prof. Steven R. Lerman and Dr. V. Judson Harward.
Advertisements

Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
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.
Java Collections Framework COMP53 Oct 24, Collections Framework A unified architecture for representing and manipulating collections Allows collections.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 7 Object Oriented Programming in Java Advanced Topics Collection.
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 Collections. Lecture Objectives To understand the concepts of Java collections To be able to implement Java programs based on 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.
Data Structures & Java Collections Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
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.
Java Collections Framework A presentation by Eric Fabricant.
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 Chapter 4.
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities.
Data Structures and Abstract Data Types "Get your data structures correct first, and the rest of the program will write itself." - David Jones.
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.
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.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Chapter 18 Java Collections Framework
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.
The Java Collections Framework Based on
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
Java 2 Collections Bartosz Walter Software Engineering II.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
1 Collections. 2 Concept A collection is a data structure – actually, an object – to hold other objects, which let you store and organize objects in useful.
Data Structures I Collection, List, ArrayList, LinkedList, Iterator, ListNode.
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
Collections ABCD ABCD Head Node Tail Node array doubly linked list Traditional Arrays and linked list: Below is memory representation of traditional.
Java Collections CHAPTER 3-February-2003
Using the Java Collection Libraries COMP 103 # T2
Sixth Lecture ArrayList Abstract Class and Interface
Chapter 19 Java Data Structures
Software Development Java Collections
Java Collections Overview
Introduction to Collections
Introduction to Collections
TCSS 143, Autumn 2004 Lecture Notes
Introduction to Collections
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
Introduction to Collections
Hashing in java.util
Part of the Collections Framework
Presentation transcript:

Lecture 6: Collections

Concept A collection is a data structure – actually, an object – to hold other objects, which let you store and organize objects in useful ways for efficient access Check out the java.util package! Lots of interfaces and classes providing a general collection framework. Programmers may also provide implementations specific to their own requirements Overview of the interfaces and concrete classes in the collection framework Collection Set SortedSet List HashSet ArrayList LinkedList TreeSet Map SortedMap WeakHashMap HashMap TreeMap ListIterator Iterator

Root interface – Collection (1) Methods working with an individual collection public int size() public boolean isEmpty() public boolean contains(Object elem) public boolean add(Object elem) Depends on whether the collection allows duplicates public boolean remove(Object elem) public boolean equals(Object o) public int hashCode() public Iterator iterator() public Object[] toArray() Returns a new array containing references to all the elements of the collection public Object[] toArray(Object[] dest) What is returned depends on whether the elements in the collection fit in dest If the type of dest is not compatible with the types of all elements in the collection, an exception is thrown

Root interface – Collection (2) Primary methods operating in bulk from another collection public boolean containsAll(Collection coll) public boolean addAll(Collection coll) Returns true if any addition succeeds public boolean removeAll(Collection coll) Returns true if any removal succeeds public boolean retainAll(Collection coll) Removes from the collection all elements that are not elements of coll public void clear() Remove all elements from this collection The SDK does NOT provide any direct implementations of the Collection interface Most of the actual collection types implement this interface, usually by implementing an extended interface such as Set or List This interface is typically used to pass collections around and manipulate them where maximum generality is desired.

Iteration - Iterator The Collection interface defines an iterator method to return an object implementing the Iterator interface. It can access the elements in a collection without exposing its internal structure. There are NO guarantees concerning the order in which the elements are returned Three defined methods in Iterator interface public boolean hasNext() – returns true if the iteration has more elements public Object next() – returns the next element in the iteration An exception will be thrown if there is no next element What’s returned is an Object object. You may need special casting! public void remove() – remove from the collection the element last returned by the iteration can be called only once per call of next, otherwise an exception is thrown

classical routine of using iterator: public void removeLongStrings (Collection coll, int maxLen) { Iterator it = coll.iterator(); while ( it.hasNext() ) { String str = (String)it.next(); if (str.length() > maxLen) it.remove() }

Iteration - ListIterator ListerIterator interface extends Iterator interface. It adds methods to manipulate an ordered List object during iteration Methods public boolean hasNext()/ public boolean hasPrevious() public Object next()/ public Object previous() public Object nextIndex()/ public Object previousIndex() When it’s at the end of the list, nextIndex() will return list.size() When it’s at the beginning of the list, previousIndex() will return -1 public void remove() – remove the element last returned by next() or previous() public void add(Object o)– insert the object o into the list in front of the next element that would be returned by next(), or at the end if no next element exists public void set(Object o) – set the element last returned by next() or previous() with o

Potential problem of Iterator/ListIterator They do NOT provide the snapshot guarantee – if the content of the collection is modified when the iterator is in use, it can affect the values returned by the methods import java.util.*; public class IteratorTest { public static void main (String args[]) { ArrayList a = new ArrayList(); a.add("1"); a.add("2"); a.add("3"); Iterator it = a.iterator(); while(it.hasNext()) { String s = (String)(it.next()); if(s.equals(“1")) { a.set(2,“changed"); } System.out.println(s); Output? 1 2 changed

Potential problem of Iterator/ListIterator (cont.) A snapshot will return the elements as they were when the Iterator/ListIterator object was created, which is unchangeable in the future If you really need a snapshot, you can make a simple copy of the collection Many of the iterators defined in the java.util package are in the type of fail-fast iterators They detect when a collection has been modified When a modification is detected, other than risk performing an action whose behavior may be unsafe, they fail quickly and cleanly by throwing an exception – ConcurrentModificationException

%> javac IteratorTest2.java %> java IteratorTest2 import java.util.*; public class IteratorTest2 { public static void main (String args[]) { ArrayList a = new ArrayList(); a.add(“1”); a.add(“2”); a.add(“3”); Iterator it = a.iterator(); a.add(“4”); while(it.hasNext()) { String s = (String)(it.next()); System.out.println(s); } %> javac IteratorTest2.java %> java IteratorTest2 Exception in thread “main” java.util.ConcurrentModificationException

List A List is an ordered Collection which allows duplicate elements. Its element indices range from 0 to (list.size()-1) It adds several methods for an ordered collection The interface List is implemented by two classes ArrayList: a resizable-array implementation of the List interface Adding or removing elements at the end, or getting an element at a specific position is simple – O(1) Adding or removing element from the middle is more expensive – O(n-i) Can be efficiently scanned by using the indices without creating an Iterator object, so it’s good for a list which will be scanned frequently LinkedList: a doubly-linked list Getting an element at position i is more expensive – O(i) A good base for lists where most of the actions are not at the end An example of using LinkedList (output)

Set and SortedSet The Set interface provides a more specific contract for its methods, but adding no new methods of its own. A Set is a Collection that contains UNIQUE elements. The SortedSet extends Set to specify an additional contract – iterators on such a set will always return the elements in a specified order By default it will be the elements’ natural order which is determined by the implementation of Comparable interface You can specify a Comparator object to order the elements instead of the natural order There are two implementations of Set in the collection framework HashSet – a Set implemented using a hashtable TreeSet – a SortedSet implemented in a balanced tree structure An example of using a HashSet

Map and SortedMap The Map interface does not extend Collection interface because a Map contains key-value pairs, not only keys. Duplicate keys are not allowed in a Map. It’s implemented by classes HashMap and TreeMap. There are methods to view the map using collections. For example: public Set keySet() and public Collection values(). The collections returned by these methods are backed by the Map, so removing an element from one these collections removes the corresponding key/value pair from the map You cannot add elements to these collections If you iterate through the key or value sets, they may return values from their respective sets in any order Interface SortedMap extends Map and maintains its keys in sorted order. Class TreeMap implements SortedMap. An example using HashMap

Synchronized wrappers and the Collections class (1) The Collections class contains static utility methods which can be roughly classified into two groups: those provide wrapped collections and those don’t. All the collection implementations provided in java.util we’ve seen so far are unsynchronized concurrent access to a Collection by multiple threads could cause indeterminate results or fatal errors. you can use synchronization wrappers for those collections that might be accessed by multiple threads to prevent potential threading problems. Methods in the Collections class to get a synchronized wrapper Collection synchronizedCollection(Collection c) Set synchronizedSet(Set s) SortedSet synchronizedSortedSet(SortedSet s) List synchronizedList(List l) Map synchronizedMap(Map m) SortedMap synchronizedSortedMap(SortedMap m)

Synchronized wrappers and the Collections class (2) The above methods return wrappers whose methods are fully synchronized, and so are safe to use from multiple threads Example Map unSyncMap = new HashMap(); Map syncMap = Collections.synchronizedMap(unSyncMap); synchMap has all relevant methods synchronized, passing all calls through to the wrapped map (unSynchMap) there is actually only one map, but with two different views. So modifications on either map is visible to the other the wrapper synchronizes on itself, so you can use syncMap to synchronize access, and then use unsyncMap safely inside such code synchronized (syncMap) { for (int i=0; i< keys.length; i++) unSyncMap.put ( keys[i], values[i] ); } HashMap synchronized wrapper syncMap unSyncMap elements

Unmodifiable wrappers and the Collections class (1) The Collections class contains a set of methods that return unmodifiable wrappers for collections: attempts to modify the returned set, whether direct or via its iterator, result in an UnsupportedOperationException The contents of an unmodifiable wrapper can change, but can only through the original collection, not through the wrapper itself Six methods to return unmodifable wrappers: Collection unmodifiableCollection(Collection c) Set unmodifiableSet(Set s) SortedSet unmodifiableSortedSet(SortedSet s) List unmodifiableList(List l) Map unmodifiableMap(Map m) SortedMap unmodifiableSortedMap(SortedMap m)

Unmodifiable wrappers and the Collections class (2) Example Original: it’s dangerous that the array’s content can be changed public String suits[]= { “Hearts”, “Clubs”, “Diamonds”, “Spades” }; Using the unmodifiable wrapper to prevent the danger: private String suitsNames[] = { public final List suits = Collections.unmodifiableList(Arrays.asList(suitNames); The unmodifiable wrapper offers read-only access to others, while the read-write access is still available to the code itself by retaining a reference to the wrapped collection (the original collection)

Abstract implementations The collection framework provides a set of abstract implementations for you to design your own implementation of relevant collection interfaces to satisfy your particular needs The set of abstract classes: AbstractCollection AbstractSet AbstractList AbstractSequentialList AbstractMap

The legacy collection types The package java.util contains some other legacy collections than those we just learned. They are still in wide use in existing code and will continue to be used until programmers shift over to the new types The set of legacy collections Enumeration – analogous to Iterator Vector – analogous to ArrayList Stack – a subclass of Vector Dictionary – analogous to Map interface Hashtable – analogous to HashMap Properties – a subclass of HashTable