Chapter 3 Collections. Objectives Define the concepts and terminology related to collections Explore the basic structures of the Java Collections.

Post on 21-Jan-2016

222 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

Transcript

Chapter 3Chapter 3

CollectionsCollections

ObjectivesObjectives

Define the concepts and terminology Define the concepts and terminology related to collectionsrelated to collections

Explore the basic structures of the Java Explore the basic structures of the Java Collections APICollections API

Discuss the abstract design of collectionsDiscuss the abstract design of collections Define a set collectionDefine a set collection Use a set collection to solve a problemUse a set collection to solve a problem Examine an array implementation of a setExamine an array implementation of a set

IntroductionIntroduction

A A collection collection is an object that gathers is an object that gathers and organizes other objects.and organizes other objects.

The collection defines the specific The collection defines the specific ways in which the ways in which the elementselements of the of the collection can be accessed and collection can be accessed and managed.managed.

Collections can be separated into two Collections can be separated into two broad categories: linear and non-broad categories: linear and non-linear.linear.

Order of the CollectionOrder of the Collection

The organization of the elements in The organization of the elements in a collection, relative to each other, a collection, relative to each other, is usually determined by one of two is usually determined by one of two things:things:

1.1. The order in which they were addedThe order in which they were added

2.2. Some inherent relationship among the Some inherent relationship among the elements themselveselements themselves

Abstract Data TypesAbstract Data Types

An An abstraction abstraction hides or ignores certain hides or ignores certain details at certain times.details at certain times.

The The interface interface is an abstraction that allows is an abstraction that allows us to control the object.us to control the object.

A A collection collection is an abstraction.is an abstraction. The user interacts with the collection The user interacts with the collection

through the interface.through the interface. The details of how the collection is The details of how the collection is

implemented is hidden from the user.implemented is hidden from the user.

Example of an InterfaceExample of an Interface

Collections ConcernsCollections Concerns

How does the collection operate, How does the collection operate, conceptually?conceptually?

How do we formally define the interface to How do we formally define the interface to the collection?the collection?

What kinds of problems does the collection What kinds of problems does the collection help us solve?help us solve?

In which various ways might we In which various ways might we implement the collection?implement the collection?

What are the benefits and costs of each What are the benefits and costs of each implementation?implementation?

Related TermsRelated Terms Data type Data type is a group of values and is a group of values and

operations defined on those values.operations defined on those values. The primitive types in Java are great The primitive types in Java are great

examples.examples. An An abstract data type abstract data type (ADT) is a data type (ADT) is a data type

whose values and operations are not whose values and operations are not inherently defined within a programming inherently defined within a programming language.language.

A A data structure data structure is the collection of is the collection of programming constructs used to programming constructs used to implement a collection.implement a collection.

Java Collections APIJava Collections API Why should we learn to program Why should we learn to program

collections, when Java already gives us a collections, when Java already gives us a set of collections?set of collections?

This set of collections is only a subset of This set of collections is only a subset of the collections you may want to use.the collections you may want to use.

The classes may not be implemented the The classes may not be implemented the way you desire.way you desire.

The study of software development The study of software development requires a deep understanding of the requires a deep understanding of the issues involved in the design of collections issues involved in the design of collections and the data structures used to implement and the data structures used to implement them.them.

Set CollectionSet Collection

Set is a collection of element with no Set is a collection of element with no duplicates.duplicates.

We can assume that there is no We can assume that there is no particular positional relationship particular positional relationship among the element of the set.among the element of the set.

A set is a non-linear collection.A set is a non-linear collection.

Conceptual View of a SetConceptual View of a Set

Common OperationsCommon Operations

Every collection has operations that Every collection has operations that allow the user to add and removeallow the user to add and remove

They usually will vary in the details.They usually will vary in the details. Additional operations such as Additional operations such as

isEmpty and size are common.isEmpty and size are common.

InterfacesInterfaces

An interface allows us to specify the An interface allows us to specify the method signatures.method signatures.

The interface name can be used as The interface name can be used as the type of the object reference, the type of the object reference, which can be assigned any object of which can be assigned any object of any class that implements the any class that implements the interface.interface.

Interfaces can also be genericInterfaces can also be generic

SetADT<T>SetADT<T>package jss2;package jss2;import java.util.Iterator;import java.util.Iterator;

public interface SetADT<T>public interface SetADT<T>{{ /** Adds one element to this set, ignoring duplicates. *//** Adds one element to this set, ignoring duplicates. */ public void add (T element);public void add (T element); /** Removes and returns a random element from this set. *//** Removes and returns a random element from this set. */ public T removeRandom ();public T removeRandom (); /** Removes and returns the specified element from this set. *//** Removes and returns the specified element from this set. */ public T remove (T element);public T remove (T element); /** Returns the union of this set and the parameter *//** Returns the union of this set and the parameter */ public SetADT<T> union (SetADT<T> set);public SetADT<T> union (SetADT<T> set); /** Returns true if this set contains the parameter *//** Returns true if this set contains the parameter */ public boolean contains (T target);public boolean contains (T target);

SetADT<T>SetADT<T> /** Returns true if this set and the parameter contain exactly/** Returns true if this set and the parameter contain exactly the same elements */the same elements */ public boolean equals (SetADT<T> set);public boolean equals (SetADT<T> set); /** Returns true if this set contains no elements *//** Returns true if this set contains no elements */ public boolean isEmpty();public boolean isEmpty(); /** Returns the number of elements in this set *//** Returns the number of elements in this set */ public int size();public int size(); /** Returns an iterator for the elements in this set *//** Returns an iterator for the elements in this set */ public Iterator<T> iterator();public Iterator<T> iterator(); /** Returns a string representation of this set *//** Returns a string representation of this set */ public String toString();public String toString();}}

UML for SetADTUML for SetADT

IteratorsIterators

An iterator is an object that provides An iterator is an object that provides the means to iterate over a the means to iterate over a collection.collection.

The iterator interface is defined in The iterator interface is defined in the Java standard class library with the Java standard class library with two primary abstract methods:two primary abstract methods:– hasNext – returns true if the collection hasNext – returns true if the collection

has more elements.has more elements.– next – returns the next element in the next – returns the next element in the

iteration.iteration.

Iterator IssuesIterator Issues

What happens if the collection is modified What happens if the collection is modified while the iterator is in use?while the iterator is in use?

Most of the collections in Java are fail-fast.Most of the collections in Java are fail-fast. Meaning they should throw an exception if Meaning they should throw an exception if

the collection is modified while the iterator the collection is modified while the iterator is in use.is in use.

However the documentation regarding this However the documentation regarding this behavior explicitly states that this is not behavior explicitly states that this is not guarnteed.guarnteed.

Iterator IssuesIterator Issues

How do you handle these How do you handle these modification issues?modification issues?

Can make iterators that allow Can make iterators that allow concurrent modificaion and reflect concurrent modificaion and reflect the changes in the collection.the changes in the collection.

Make iterators that iterate over a Make iterators that iterate over a snapshot of the collection so snapshot of the collection so modification makes no changes to modification makes no changes to the iterators.the iterators.

Implementing a Set with ArraysImplementing a Set with Arrays

Design Questions:Design Questions:– How do you implement a non-linear How do you implement a non-linear

collection with a linear data structure?collection with a linear data structure?– How do you manage the fact that the How do you manage the fact that the

size of an array is fixed?size of an array is fixed?

Managing CapacityManaging Capacity

What do we do when the array is What do we do when the array is full?full?– We could throw an exception.We could throw an exception.– We could return a success indication We could return a success indication

from the add method that the use can from the add method that the use can check.check.

– We could increase the capacity when it We could increase the capacity when it is full.is full.

Array implementation of a setArray implementation of a set

ArraySet - ConstructorsArraySet - Constructors

ArraySet - size and isEmptyArraySet - size and isEmpty

ArraySet - addArraySet - add

ArraySet - expandCapacityArraySet - expandCapacity

ArraySet - addAllArraySet - addAll

ArraySet - removeRandomArraySet - removeRandom

ArraySet - removeArraySet - remove

ArraySet - unionArraySet - union

ArraySet - containsArraySet - contains

ArraySet - equalsArraySet - equals

ArraySet - equals (continued)ArraySet - equals (continued)

ArraySet - iteratorArraySet - iterator

Listing 3.4Listing 3.4

Listing 3.4 Listing 3.4 (cont.)(cont.)

Listing 3.4 Listing 3.4 (cont.)(cont.)

Analysis of Analysis of ArraySetArraySet Adding an element to the set is O(n) Adding an element to the set is O(n)

because of the need to check to see if the because of the need to check to see if the element is already in the setelement is already in the set

Expanding the capacity is also O(n)Expanding the capacity is also O(n) Removing a particular element, because Removing a particular element, because

it must be found, is O(n)it must be found, is O(n) Removing a random element is O(1)Removing a random element is O(1) Adding all elements of another set is O(n)Adding all elements of another set is O(n) The union of two sets is O(n+m), where m The union of two sets is O(n+m), where m

is the size of the second setis the size of the second set

top related