Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations

Presentation on theme: "CE203 - Application Programming Autumn 2013CE203 Part 41 Part 4."— Presentation transcript:

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

2 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();

3 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.

4 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.

5 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();

6 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.

7 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.

8 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.

9 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 ).

10 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.

11 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);

12 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.

13 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.

14 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.

15 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.

16 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.

17 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.

18 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 ).

19 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.

20 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);

21 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.

22 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.

23 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.

24 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.set(s); }

25 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);

26 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);

27 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).

28 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());

29 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.

30 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

31 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(); }

32 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.

33 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.

34 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 =; System.out.println( e.getKey()+":"+e.getValue()); }

35 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 (<0) it.remove();

36 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 =; if (e.getValue().intValue()<0) e.setValue(0); }

37 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.

38 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.

Download ppt "CE203 - Application Programming Autumn 2013CE203 Part 41 Part 4."

Similar presentations

Ads by Google