CE203 - Application Programming Autumn 2013CE203 Part 41 Part 4.

Slides:



Advertisements
Similar presentations
Chapter 23 Organizing list implementations. This chapter discusses n The notion of an iterator. n The standard Java library interface Collection, and.
Advertisements

Introduction to Java 2 Programming Lecture 5 The Collections API.
Introduction to Computation and Problem Solving Class 32: The Java® Collections Framework Prof. Steven R. Lerman and Dr. V. Judson Harward.
Java Programming: Advanced Topics 1 Collections and Utilities.
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
AITI Lecture 19 Linked List Adapted from MIT Course 1.00 Spring 2003 Lecture 26 and Tutorial Note 9 (Teachers: Please do not erase the above note)
Concrete collections in Java library
JAVA Programming (Session 7) When you are willing to make sacrifices for a great cause, you will never be alone. Instructor:
Double-Linked Lists and Circular Lists
The List ADT Textbook Sections
Copyright © 2013 by John Wiley & Sons. All rights reserved. HOW TO CREATE LINKED LISTS FROM SCRATCH CHAPTER Slides by Rick Giles 16 Only Linked List Part.
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.
Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
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++)
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
Collections Sets - no duplicates Lists - duplicates allowed Maps - key / value pairs A collection is an Object which contains other Objects. There are.
15-Jun-15 Lists in Java Part of the Collections Framework.
1 L41 Collections (1). 2 OBJECTIVES  What collections are.  To use class Arrays for array manipulations.  To use the collections framework (prepackaged.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
© The McGraw-Hill Companies, 2006 Chapter 17 The Java Collections Framework.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L15 (Chapter 22) Java Collections.
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.
Chapter 19 Java Data Structures
Java's Collection Framework
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
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.
CS-2851 Dr. Mark L. Hornick 1 Tree Maps and Tree Sets The JCF Binary Tree classes.
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.
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.
1 Java's Collection Framework By Rick Mercer with help from The Java Tutorial, The Collections Trail, by Joshua BlockThe Collections Trail.
(c) University of Washington14-1 CSC 143 Java Collections.
111 © 2002, Cisco Systems, Inc. All rights reserved.
CSE 143 Lecture 4 ArrayList Reading: 10.1 slides created by Marty Stepp
Chapter 18 Java Collections Framework
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
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
Java Programming: From the Ground Up Chapter 17 The Java Collections Framework.
List Interface and Linked List Mrs. Furman March 25, 2010.
Priority Queues. Priority Queue ADT A priority queue stores a collection of entries Each entry is a pair (key, value) Main methods of the Priority Queue.
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.
Starting Out with Java From Control Structures through Data Structures by Tony Gaddis and Godfrey Muganda Collections in Java.
Data Structures I Collection, List, ArrayList, LinkedList, Iterator, ListNode.
CS 46B: Introduction to Data Structures July 21 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
1 Maps, Stacks and Queues Maps Reading:  2 nd Ed: 20.4, 21.2, 21.7  3 rd Ed: 15.4, 16.2, 16.7 Additional references: Online Java Tutorial at
Collections Dwight Deugo Nesa Matic
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Introduction to Java Collection. Java Collections What are they? –A number of pre-packaged implementations of common ‘container’ classes, such as LinkedLists,
Collections ABCD ABCD Head Node Tail Node array doubly linked list Traditional Arrays and linked list: Below is memory representation of traditional.
Chapter 19 Java Data Structures
Introduction to Collections
Introduction to Collections
Introduction to Collections
Collections Framework
Part of the Collections Framework
Presentation transcript:

CE203 - Application Programming Autumn 2013CE203 Part 41 Part 4

Autumn 2013CE203 Part 42 Sorted Sets 1 The SortedSet interface extends the Set interface by adding methods that can be applied efficiently to sets whose elements are stored in order. These extra methods are: public Object first(); public Object last(); public SortedSet headSet(Object o); public SortedSet tailSet(Object o); public SortedSet subSet(Object o1, Object o2); public Comparator comparator();

Autumn 2013CE203 Part 43 Sorted Sets 2 The iterator for a sorted set will visit the elements in ascending order. The first method returns the smallest element, whereas last returns the largest element. Each of these will throw a NoSuchElementException if the set is empty. The headSet method returns a sorted set containing all of the elements of the set that are less than to the object supplied as an argument. If there are no such elements an empty set will be returned. The tailSet method is similar but the result contains elements greater than or equal to the argument.

Autumn 2013CE203 Part 44 Sorted Sets 3 The subSet method returns a set containing all of the elements that are greater than or equal to the first argument and less than the second argument. An IllegalArgumentException will be thrown if the first argument is greater than the second. An empty set will be returned if the arguments are equal.

Autumn 2013CE203 Part 45 Sorted Sets 4 The sets returned by headSet, tailSet and subSet are views of part of the original set, rather than copies, so if any additions or removals are applied to the subset the contents of the original set will also be changed. Hence, for example, we could remove all elements less than 10 from a sorted set of integers using mySet.headSet(10).clear();

Autumn 2013CE203 Part 46 Sorted Sets 5 When a sorted set is created it is necessary to specify the ordering that will be used to compare elements. The usual choice is to use the compareTo method from the Comparable interface. In this case all elements that are inserted into the set must be objects of classes that implement this interface. An alternative approach, to be used when we wish to sort elements according to some other ordering, is to supply a Comparator object. The comparator method from the SortedSet interface will return the Comparator object for the set if one has been supplied; otherwise it will return null.

Autumn 2013CE203 Part 47 The TreeSet Class 1 The TreeSet class implements the SortedSet interface using a tree structure. Note that if we use a set of type TreeSet or TreeSet methods such as add, addAll, remove, removeAll and contains can throw an exception of type ClassCastException if the arguments are of inappropriate types for comparisons. Wherever possible specific types such as TreeSet should be used so that the compiler can check that the arguments are of the correct type.

Autumn 2013CE203 Part 48 The TreeSet Class 2 The TreeSet class has four constructors. The first constructor has no arguments and creates an initially-empty set that will be ordered using the compareTo method. The second constructor has an argument of type SortedSet and creates a set containing the same elements as its argument, ordered using the same ordering.

Autumn 2013CE203 Part 49 The TreeSet Class 3 The third constructor has an argument of type Collection and creates a set containing all of the elements of the argument, ordered using compareTo. Note that a ClassCastException may be thrown if the collection contains objects from classes that do not implement Comparable or contains a pair of objects that cannot be compared, for example a number and a string. (This problem cannot arise if we used a parameterised type that implements Comparable since the constructor for TreeSet takes an argument of type Collection ).

Autumn 2013CE203 Part 410 The TreeSet Class 4 The fourth constructor has an argument of type Comparator and creates an initially-empty set that will be ordered using that comparator. If the set has type TreeSet the argument must be of type Comparator.

Autumn 2013CE203 Part 411 Lists 1 The List interface extends the Collection interface by adding additional methods appropriate for use with lists. public Object get(int i); public int indexOf(Object o); public int lastIndexOf(Object o); public void add(int i, Object o); public void addAll(int i, Collection c); public Object remove(int i); public void set(int i, Object o); public List subList(int i, int j); public ListIterator listIterator(); public ListIterator listIterator(int i);

Autumn 2013CE203 Part 412 Lists 2 The methods indexOf and lastIndexOf behave in the same way as already described for the Vector class; as with arrays and vectors, indexing starts at 0. The methods get, add, set and remove take a location as the first argument and return, insert, replace or remove the element at that location; if the argument is out of range an exception of type IndexOutOfBoundsException will be thrown; the result returned by the remove method is a reference to the object that has been removed.

Autumn 2013CE203 Part 413 Lists 3 We can of course also use the inherited add and remove methods which take a single argument of type Object. The former adds to the end of the list and the latter removes the first instance. The addAll method will insert all of the elements of the argument collection into the list, starting at the position specified by the first argument. The order in which the elements are added is the order in which they would be visited by an iterator returned by the argument’s iterator method.

Autumn 2013CE203 Part 414 Lists 4 The s ubList method returns a view of part of the list to which it is applied; the portion returned by myList.subList(i,j) will run from position i to position j-1. An IndexOutOfBoundsException will be thrown if either of the arguments is out of range or if i is greater than j ; an empty sub-list will be returned if i and j are equal. Changes to the sub-list will affect the original list in a similar way to changes to subsets of sorted sets.

Autumn 2013CE203 Part 415 Lists 5 The two listIterator methods return iterators of type ListIterator ; the version without an argument will return an iterator whose place-marker starts in front of the first element of the list, whereas the other will return an iterator whose place-marker is initially positioned in front of the item whose index is specified by its argument. The ListIterator interface extends the Iterator interface so we can use the iterators returned by these methods in the same way as iterators for sets; however, the ListIterator interface provides additional methods that can be used when traversing the list.

Autumn 2013CE203 Part 416 Lists 6 There are three classes in the Java library that implement the List interface: Vector (as already seen), ArrayList and LinkedList. The ArrayList class is very similar to the Vector class but has an extra method called ensureCapacity that takes an argument of type int and increases the capacity if it is currently smaller than the argument. This class does not have …elementAt methods – the methods of the List interface can be used to perform the same tasks For large collections the ArrayList class will perform more efficiently than the Vector class.

Autumn 2013CE203 Part 417 Lists 7 The LinkedList class provides an implementation of the List interface using a doubly-linked list (i.e. a list in which each cell has references to both the next and previous cells). This class can provide more efficient insertion and removal than the ArrayList class since items do not have to be shifted. However, the need to locate the appropriate position when these operations are performed means that much of this efficiency benefit is lost if the position is near the middle of the list.

Autumn 2013CE203 Part 418 Lists 8 The LinkedList class provides six extra methods for programming convenience (although all of their operations can be performed using methods specified by the List interface). These methods are getFirst, getLast, removeFirst and removeLast (all of which have no argument and return a result of type Object ), and addFirst and addLast (which are void and have an argument of type Object ).

Autumn 2013CE203 Part 419 Lists 9 The LinkedList class has just two constructors, one with no argument and one with an argument of type Collection. The latter copies the elements of the collection into the new list in the order in which an iterator would visit them. The ArrayList class has three constructors, two as described above and a third which takes an initial capacity as an argument.

Autumn 2013CE203 Part 420 List Iterators 1 The ListIterator interface extends the Iterator interface adding additional methods that can be used when traversing lists. These methods are public boolean hasPrevious(); public Object previous(); public int nextIndex(); public int previousIndex(); public void set(Object o); public void add(Object o);

Autumn 2013CE203 Part 421 List Iterators 2 A list iterator, like any other iterator, has a place-marker that is located between two adjacent elements; we can move this place-marker in either direction so in addition to the hasNext and next methods there are previous and hasPrevious methods. The nextIndex and previousIndex methods can be used to obtain the positions in the list of the elements on either side of the place-marker.

Autumn 2013CE203 Part 422 List Iterators 3 The add method adds an object to the list immediately in front of the item to the right of the place-marker (i.e. the item that would be returned if next were called); if the place- marker is at the end of the list the item will be added to the end of the list.

Autumn 2013CE203 Part 423 List Iterators 4 The set method changes the contents of the list, replacing the item that was returned by the last call to either next or previous by the item supplied as an argument. An exception of type IllegalStateException will be thrown if there has been no call to either next or previous, and also if either of the add or remove methods has been called since the last call to next or previous.

Autumn 2013CE203 Part 424 List Iterators 5 We can make use of the set method of the ListIterator class to write a method that replaces all the strings in a list by upper-case versions. public static void upperCase(List l) { ListIterator it = l.listIterator(); while (it.hasNext()) String s = it.next().toUpperCase(); it.set(s); }

Autumn 2013CE203 Part 425 The Collections Class 1 The Collections class provides a number of static methods that can perform useful operations on collections. These include min and max to find the smallest or largest element in a collection and frequency, which returns the number of occurrences of an object. Since these methods are static we have to supply the identity of the collection as the first argument, e.g. int n = Collections.frequency(mySet, 7); Integer small = Collections.min(myIntgrList);

Autumn 2013CE203 Part 426 The Collections Class 2 The Collections class also provides several methods that operate only on lists. These include sort to sort the contents of the list into ascending order, reverse to reverse the order of the elements and shuffle to rearrange the elements randomly. These methods change the contents of the list to which they are applied and do not return a new copy, e.g. Collections.sort(myList);

Autumn 2013CE203 Part 427 The Collections Class 3 The min, max and sort methods normally use compareTo to compare elements so the elements of the collection should be of a class that implements Comparable. However there are also versions that take as a second argument an object that implements the Comparator interface allowing an ordering other than the natural one to be used for comparison. Assuming that a Person class has a compareTo method based on names but if we wish to sort a list by dates of birth we could use the code on the following slide (which assumes that the Date class has a compareTo method).

Autumn 2013CE203 Part 428 The Collections Class 4 class DOBComp implements Comparator { public int compare(Person p1, Person p2) { int x = p1.dateOfBirth().compareTo (p2.dateOfBirth()); if (x!=0) return x; else return p1.compareTo(p2); // must not return 0 if different people // have same date of birth } } …… Collections.sort(personList, new DOBComp());

Autumn 2013CE203 Part 429 The Map Interface 1 The Java Collections Framework provides a further kind of collection. A map is a collection of pairs of entries each comprising a key and a value. Elements of a map must have unique keys, but there may be more than one element with the same value. The Map interface does not extend the Collection interface but provides similar methods. The interface is shown on the following slides.

Autumn 2013CE203 Part 430 The Map Interface 2 public interface Map { public boolean isEmpty(); public int size(); public boolean containsKey(Object k); public boolean containsValue(Object v); public Object get(Object key); public void clear(); public Object put(Object k, Object v); public void putAll(Map m); public Object remove(Object key); // continued on next slide

Autumn 2013CE203 Part 431 The Map Interface 3 // public interface Map continued public Set entrySet(); public Set keySet(); public Collection values(); public boolean equals(Object o); public int hashCode(); }

Autumn 2013CE203 Part 432 The Map Interface 4 The behaviour of many of the methods is similar to the corresponding Collection methods and will not be described here. The get method returns the value associated with the key supplied as an argument; null will be returned if there is no entry with that key. The put method will add a new entry to the map. If there was an existing entry with the same key this will be replaced, and its previous value returned; otherwise null will be returned.

Autumn 2013CE203 Part 433 The Map Interface 5 The argument to the remove method is a key; the value returned will be the value in the entry that has been removed, or null if there was no entry with that key. The Map interface has no methods that return iterators; however we can iterate through the contents of the map using an iterator for the set returned by entrySet or keySet or for the collection returned by values. These return views of the map rather than new sets so any changes made while iterating will alter the contents of the map. If a key or value is removed from the collection the entry will be removed from the map.

Autumn 2013CE203 Part 434 The Map Interface 6 The values method returns an object of type Collection rather than Set since there may be duplicate elements. The elements of the set returned by entrySet are of type Map.Entry. This interface has methods getKey, getValue and setValue. To print the contents of a map m we could use code such as Set s = m.entrySet(); Iterator it = s.iterator(); while (it.hasNext()) { Map.Entry e = it.next(); System.out.println( e.getKey()+":"+e.getValue()); }

Autumn 2013CE203 Part 435 The Map Interface 7 The parameterised-type version of Map uses two type parameters, the types of the keys and of the values. If m2 is of of type Map we could use the following code to remove all entries whose values are negative. Collection c = m2.values(); Iterator it = c.iterator(); while (it.hasNext()) if (it.next().intValue()<0) it.remove();

Autumn 2013CE203 Part 436 The Map Interface 8 To modify the values of entries we can apply the setValue method from Map.Entry ; to replace all the negative values in m2 with zero we could use Set > s = m2.entrySet(); Iterator > it = s.iterator(); while (it.hasNext()) { Map.Entry e = it.next(); if (e.getValue().intValue()<0) e.setValue(0); }

Autumn 2013CE203 Part 437 Map Classes 1 The Java Collections framework contains two classes that implement the Map interface, HashMap and TreeMap. These are similar to HashSet and TreeSet and arrange the entries according to their keys. For efficient use of HashMap the key class should have a suitable hashCode method. The class has four constructors: three correspond to three of the HashSet constructors (described earlier) and behave in the same way, and the fourth is a constructor with an argument of type Map, which is provided instead of the one with an argument of type Collection.

Autumn 2013CE203 Part 438 Map Classes 2 The TreeMap class implements an interface called SortedMap that extends the Map interface by defining six methods similar to those of SortedSet ; these are called firstKey, lastKey, headMap, tailMap, subMap and comparator. Since the class sorts the entries according to their keys the methods that take objects as arguments use these object as keys. The class has four constructors similar to those of the TreeSet class. In order to use TreeMap when a constructor with a comparator argument has not been used the keys must be of a type that implements Comparable.