380 likes | 508 Views
CE203 - Application Programming. Part 4. 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:
E N D
CE203 - Application Programming Part 4 CE203 Part 4
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 SortedSetheadSet(Object o); public SortedSettailSet(Object o);public SortedSetsubSet(Object o1, Object o2);public Comparator comparator(); CE203 Part 4
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. CE203 Part 4
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. CE203 Part 4
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(); CE203 Part 4
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. CE203 Part 4
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<Object> 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<Integer> should be used so that the compiler can check that the arguments are of the correct type. CE203 Part 4
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 SortedSetand creates a set containing the same elements as its argument, ordered using the same ordering. CE203 Part 4
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<T> takes an argument of type Collection<T>). CE203 Part 4
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<T> the argument must be of type Comparator<T>. CE203 Part 4
Lists 1 The List interface extends the Collection interface by adding additional methods appropriate for use with lists. public Object get(inti);public intindexOf(Object o);public intlastIndexOf(Object o);public void add(inti, Object o);public void addAll(inti, Collection c);public Object remove(inti);public void set(inti, Object o);public List subList(inti, int j);public ListIteratorlistIterator();public ListIteratorlistIterator(inti); CE203 Part 4
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. CE203 Part 4
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. CE203 Part 4
Lists 4 The subList 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. CE203 Part 4
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. CE203 Part 4
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. CE203 Part 4
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. CE203 Part 4
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). CE203 Part 4
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. CE203 Part 4
List Iterators 1 The ListIterator interface extends the Iterator interface adding additional methods that can be used when traversing lists. These methods are public booleanhasPrevious();public Object previous();public intnextIndex();public intpreviousIndex();public void set(Object o);public void add(Object o); CE203 Part 4
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. CE203 Part 4
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. CE203 Part 4
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. CE203 Part 4
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 byupper-case versions. public static void upperCase(List<String> l){ ListIterator<String> it = l.listIterator(); while (it.hasNext()) String s = it.next().toUpperCase(); it.set(s); } CE203 Part 4
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); CE203 Part 4
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); CE203 Part 4
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). CE203 Part 4
The Collections Class 4 class DOBComp implements Comparator<Person>{ 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()); CE203 Part 4
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. CE203 Part 4
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 CE203 Part 4
The Map Interface 3 // public interface Map continued public Set<Map.Entry> entrySet(); public Set keySet(); public Collection values(); public boolean equals(Object o); public int hashCode();} CE203 Part 4
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. CE203 Part 4
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. CE203 Part 4
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<Map.Entry> s = m.entrySet();Iterator<Map.Entry> it = s.iterator();while (it.hasNext()){ Map.Entry e = it.next();System.out.println(e.getKey()+":"+e.getValue());} CE203 Part 4
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<Character,Integer> we could use the following code to remove all entries whose values are negative. Collection<Integer> c = m2.values();Iterator<Integer> it = c.iterator();while (it.hasNext()) if (it.next().intValue()<0)it.remove(); CE203 Part 4
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<Map.Entry<Character,Integer>> s = m2.entrySet();Iterator<Map.Entry<Character,Integer>> it =s.iterator();while (it.hasNext()){ Map.Entry<Character,Integer> e = it.next(); if (e.getValue().intValue()<0)e.setValue(0);} CE203 Part 4
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. CE203 Part 4
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. CE203 Part 4