Java Unit 6

17
Unit 6: Java Collection Framework and Iterators Abstract Data Type (ADT) and Data Structure ADT: ways to organize data in the computing environment; it provides specification of o Set of data that can be stored o Set of operations that can be performed on the data - It is abstract (can be used on any types) Data Structure: implementation of an ADT within a programming language (organization of data) ADT Terminology Collection: an ADT that contains a group of objects/items o Linear: Ordered (eg name of students in class) o NonLinear: - Unordered (eg bag of groceries) - Hierarchical (eg a file system on pc) - Graph (eg airline connections between cities of Canada) Containers: a class that implements the collection Types of ADTs Bag: Unordered collection, may contain duplicates List: Numbers its items Stack: Orders sequentially (LIFO) Queue: Orders sequentially (FIFO) Dictionary: Pairs of Items (key and value) ; can be sorted or not Tree: Hierarchy arrangement Graph: Generalization of a tree

description

: Java Collection Framework and Iterators

Transcript of Java Unit 6

Unit 6: Java Collection Framework and Iterators

Abstract Data Type (ADT) and Data StructureADT: ways to organize data in the computing environment; it provides specification of Set of data that can be stored Set of operations that can be performed on the data- It is abstract (can be used on any types)Data Structure: implementation of an ADT within a programming language (organization of data)

ADT TerminologyCollection: an ADT that contains a group of objects/items Linear: Ordered (eg name of students in class) NonLinear: - Unordered (eg bag of groceries) - Hierarchical (eg a file system on pc) - Graph (eg airline connections between cities of Canada)Containers: a class that implements the collection

Types of ADTsBag: Unordered collection, may contain duplicatesList: Numbers its itemsStack: Orders sequentially (LIFO)Queue: Orders sequentially (FIFO)Dictionary: Pairs of Items (key and value) ; can be sorted or notTree: Hierarchy arrangementGraph: Generalization of a tree

Java Collection Framework Hierarchy

-The Java Collections Framework supports three types of collections: Sets, Lists, and Queues (Subinterfaces of Collection)

The Collection Interface

The Set Interface (extends Collection)-Intance of set contains NO DUPLICATE ELEMENTS The concrete classes ensure that no duplicate elemtns can be added to the set

The AbstractSet Class (abstract class)-extends AbstractCollection (implements toString() method) and implements Set-provides concrete implementations for equals() and the hashCode() methods (from Object Class)-the hash code of a set is the sum of the hash codes of all elements in the set-size() and interator() NOT IMPLEMENTED in this class, therefore its an abstract class

The HashSet Class-implements Set (thus stores DUPLICATE-FREE elements)Set myset = new HashSet()

myset.add()

then..Interator myiterator = myset.iterator()

while (myiterator.hasNext()) { System.out.print (myiterator.next().toUpperCase() + , ) }

ORfor (String n: myset) { System.out.print (n.toString() + , ) }

The SortedSet Interface and the TreeSet Class-SortedSet: sub-interface of Set (guarantees that elements in the set are sorted)-TreeSet: concrete class that implements SortedSet (use Iterator to traverse elements in sorted order)-NO PRIMITIVE DATA TYPE can be used on the tag ; use wrapper class instead-Can add objects into a tree set as long as they can be COMPARED w/ each other. TWO ways: Use the Comparable interface (use compareTo() method). (String, Date, Calendar, and primitive wrapper classes (e.g. Integer) implements this interface) -> known as natural order Specify a comparator for the elements in the set if the class for the elements does not implement the comparable interface -> known as order by comparatorSet sortedSet = new TreeSet (myset)

Set myset = new HashSet ()myset.add()

System.out.println (sortedSet)

ORSet myset = new TreeSet ()

System.out.println (myset)

myset.add()

The Comparator Interface-used when elements you want to put in Tree Set are not instances of Comparable or are not comparable-create a class that implementsthe java.util.Comparator interface (two methods: compare and equals)Set set = new TreeSet (new ObjectTypeComparator() )

public int compare (Object element1, Object element2); greater = 1, equal = 0, less = -1

public class ObjectTypeComparator implements Comparator {.}

public boolean equals (Object element)

The List Interface-allows to store duplicate elements in a collection-user can access the element of a list by index

ArrayList and LinkedList-concrete implementations of the List Interface-ArrayList: allows only insertion/removal of elements at end-LinkedList: allows insertion/removal of elements at any place in the list***Note: An array is fixed once it is created, therefore if application doesnt require insert/delete, most efficient is the array, no need for list.

The Collections Class-contains various static methods for operating on collections and maps, creating synchronized collection classes, and for creating read-only collection classes

The Vector Class

The Stack Class (LIFO)-can only access elements from the top of the stack

Queues and Priority Queues (FIFO)In priority queue, elements are assigned priorities. When accessing elements, elements with highest priority is removed first

The Map Interface (aka dictionary)-maps keys (indices) to the elements In List, the indices are integers, but in Map, the keys can be any objects

The Map.Entry Interface UML Diagram-the entrySet() method in the Map interface returns a set of objects that implement the Map.Entry interface where Entry is an inner interface for the Map interface-Each object in the set is a specific key/value pair in the underlying map

Concrete Map Classes

HashMap and TreeMap Classes-Hashmap Class: efficient for location a value (not ordered) , inserting/deleting a mapping-TreeMap Class: implements SortedMap efficient for traversing keys in sorted order; maintains the mapping in ascending order of keysLinkedHashMap-LinkedHashMap Class: extends HashMap with a linked list implementation that supports an ordering of the entries in the map-the entries can be retrieved in the order in which: they were inserted into the map (insertion order) OR they were last accessed, from least recently accessed to most recently (access order)NO-ARG constructor constructs a LinkedHashMap w/ insertion orderLinkedHashMap (initialCapacity, loadFactor, true)

access order LinkedHashMap (false for insertion):

The Arrays Class (java.util.Arrays)Arrays Class: contains various static methods for sorting and searching arrays, comparing, and filling contains static method for converting array to a list (Arrays.asList())

Iterator: What is an Iterator?-Iterator: a program component that steps through a collection of data keeps track of its progress during the iteration can tell whether next entry exists and if so, returns a reference to it Iterator may be manipulated Asked to advance to next entry Give a reference to current entry Modify the list as it passes throughThe Interface Iterator-specifies a generic type for entries

-hasNext(): returns true if iterator has another (next) entry to return-next(): returns a reference to the next entry (if exists) and advances iterator by one position Throws NoSuchElementException if iterator had reached end already (hasNext() is false)-remove(): removes the collection of data the last entry that next() returned Precondition: next() has been called, and remove() has not been called since then Throws IllegalStateException if next() is not called before the call for remove() Throws UnsupportedOperationException if this iterator does not permit a remove operation-Position of an iterator (iterator cursor) is positioned before the first, between two, or after last entry

The Interface ListIterator-extends the interface Iterator-enables either direction traversal-allows modification of list during iteration-same as Iterator with hasNext(), next(), and remove()-hasPrevious(): returns true if iterator has another (next) entry to return when traversing BACKWARDS-previous(): returns a reference to the previous entry (if exists) and moves iterator back one position Throws NoSuchElementException if iterator at beginning already (hasPrevious() is false)****for the following*** note that iterator numbers the list entries from 0 instead of 1-nextIndex(): returns the index of the next entry; if no entry (at end), returns list size-previousIndex(): returns the index of the previous entry; if no entry (at beginning), returns -1-add (T newEntry): adds an entry to the list just before the entry that next() would have returned adds an entry to the list after the entry that previous() would have returned Iterator cursor will be after the new entry after addition, call to previous() would return the new entry, but next() would behave the same throws ClassCastException if class of newEntry prevents the addition to list throws IllegalArgumentException if some other aspect of newEntry prevents addition to list throws UnsupportedOperationException if this iterator does not permit an add operation-set (T newEntry): replaces the last entry in the list that either next() or previous() has returned Precondition: next() or previous() called, but remove() or add() not called since then throws ClassCastException if class of newEntry prevents the addition to list throws IllegalArgumentException if some other aspect of newEntry prevents addition to list throws IllegalStateException if next() or previous() not been called or if remove() or add() called throws UnsupportedOperationException if this iterator does not permit a set operation