Docsity

Java Arrays and Collections: Sorting, Searching, and Comparing, Study notes of Computer Science

Toggle sidebar
bg1
1
The Java 2 Collections - Finally, Some News You Can Use by Chuck Allison
Arrays: Algorithms for processing Arrays:
- binarySearch: returns the zero-based index of the element you're after, if it's in the array;
otherwise it returns -pos – 1, where pos is the index of the position it should occupy.
- equals
- fill
- sort : ascending order only
class ArraysTest {
static void search(int[] a, int n) {
int where = Arrays.binarySearch(a, n);
if (where < 0) {
where = -(where + 1);
if (where == a.length) System.out.println("Append " + n + " to end of list");
else System.out.println("Insert " + n + " before " + a[where]);
}
else System.out.println("Found " + n + " in position " + where);
}
public static void main(String[] args) {
// Build Array:
int[] array = {88, 17, -10, 34, 27, 0, -2};
Arrays.sort(array);
search(array, -10);
System.out.println("array == array? " + Arrays.equals(array,array));
int[] ones = new int[array.length];
Arrays.fill(ones, 1);
}
}
For descending order, use a Comparator: an object that implements the following interface:
public interface Comparator {
int compare(Object o1, Object o2);
}
The compare method must behave like C's strcmp function by returning a negative number if o1
precedes o2, zero if they are equal, or a positive number otherwise.
class Descending implements Comparator {
public int compare(Object o1, Object o2) {
Comparable c1 = (Comparable) o1;
Comparable c2 = (Comparable) o2;
return -c1.compareTo(c2); // Integers provide compareTo()
}
}
or simply: static Comparator desc = Collections.reverseOrder();
pf3
pf4
pf5
pf8
pf9
pfa
pfd

Partial preview of the text

Download Java Arrays and Collections: Sorting, Searching, and Comparing and more Study notes Computer Science in PDF only on Docsity!

The Java 2 Collections - Finally, Some News You Can Use by Chuck Allison

Arrays : Algorithms for processing Arrays:

- binarySearch: returns the zero-based index of the element you're after, if it's in the array; otherwise it returns -pos – 1, where pos is the index of the position it should occupy. - equals - fill - sort : ascending order only

class ArraysTest { static void search(int[] a, int n) { int where = Arrays.binarySearch(a, n); if (where < 0) { where = -(where + 1); if (where == a.length) System.out.println("Append " + n + " to end of list"); else System.out.println("Insert " + n + " before " + a[where]); } else System.out.println("Found " + n + " in position " + where); } public static void main(String[] args) { // Build Array: int[] array = {88, 17, -10, 34, 27, 0, -2}; Arrays.sort(array); search(array, -10); System.out.println("array == array? " + Arrays.equals(array,array)); int[] ones = new int[array.length]; Arrays.fill(ones, 1); } }

For descending order, use a Comparator : an object that implements the following interface: public interface Comparator { int compare(Object o1, Object o2); }

The compare method must behave like C's strcmp function by returning a negative number if o precedes o2, zero if they are equal, or a positive number otherwise. class Descending implements Comparator { public int compare(Object o1, Object o2) { Comparable c1 = (Comparable) o1; Comparable c2 = (Comparable) o2; return -c1.compareTo(c2); // Integers provide compareTo() } }

or simply: static Comparator desc = Collections.reverseOrder();

class ArraysTest2 { static Descending desc = new Descending(); static void search(Object[] a, Object n) { int where = Arrays.binarySearch(a, n, desc ); if (where < 0) { where = -(where + 1); if (where == a.length) System.out.println("Append " + n + " to end of list"); else System.out.println("Insert " + n + " before " + a[where]); } else System.out.println("Found " + n +" in position " + where); } public static void main(String[] args) { // Build Array: Integer[] array = {new Integer(88), new Integer(17), new Integer(-10), new Integer(34), new Integer(27), new Integer(0), new Integer(-2)}; Arrays.sort(array, desc ); search(array, new Integer(-10)); } }

A Comparable object implements the method int compareTo(Object o) , which also behaves like C's strcmp.

public class Person implements Comparable, Cloneable { private String name; private int year; private int month; private int day; public Person(String name, int year, int month, int day) { this.name = new String(name); this.year = year; this.month = month; this.day = day; } public String getName() { return name; } public Object clone() { try {Person p = (Person) super.clone(); p.name = new String(name); return p;} catch (CloneNotSupportedException x) { throw new InternalError(x.toString()); } } public boolean equals(Object o) { if (o instanceof Person) { Person p = (Person) o; return name.equals(p.name)&& year == p.year&&month==p.month&&day == p.day; } else return false; } public int hashCode() { // ensure different persons get different results int hval = name.hashCode()+year; hval = (hval << 4) + month; hval = (hval << 4) + day; return hval; } public String toString() {return '{' + name + ',' + month + '/' + day + '/' + year + '}';}

Collections:

Collections are containers that implement the Collection interface: Interface Collection { boolean add(Object o); boolean addAll(Collection c); void clear(); boolean contains(Object o); boolean containsAll(Collection c); boolean equals(Object o); int hashCode(); boolean isEmpty(); Iterator iterator(); boolean remove(Object o); boolean removeAll(Collection c); boolean retainAll(Collection c); int size(); Object[] toArray(); Object[] toArray(Object[] a); }

The Collection interface is further refined into List and Set: Interface List extends Collection { void add(int index, Object element) Object get(int index) int indexOf(Object o) int lastIndexOf(Object o) ListIterator listIterator() ListIterator listIterator(int index) Object remove(int index) Object set(int index, Object element) int size() List subList(int fromIndex, int toIndex) }

Set is identical to Collection but no duplicates are allowed.

List s are ordered sequences that support direct indexing and bidirectional traversal. Java 2 comes with LinkedList and ArrayList as implementations for List.

Vector is also there for historical reasons, but ArrayList is preferred over Vector in new code.

LinkedList implements a doubly-linked list, and is optimized for inserting and removing elements anywhere in a list. ArrayList is simply an expandable array, and is preferred when you need to use random access to list elements.

class ListTest { public static void test(List x) { Object p = x.get(2); if (x.contains(p)) System.out.println("Found " + p); // Do a search: int index = x.indexOf(p); // Do another: if (index != -1) System.out.println("Found " + p + " in position " + index); Collections.sort(x); index = Collections.binarySearch(x, p); if (index >= 0) System.out.println("Found " + p + " in position " + index); System.out.println("max == " + Collections.max(x)); System.out.println("min == " + Collections.min(x)); Comparator desc = Collections.reverseOrder(); System.out.println("max (desc) == " + Collections.max(x, desc)); System.out.println("min (desc) == " +Collections.min(x, desc)); Collections.shuffle(x); iterate(x); } public static void iterate(Collection c) { Iterator i = c.iterator(); while (i.hasNext()) System.out.println(i.next()); }

public static void main(String[] args) { ArrayList array = new ArrayList(); // Build ArrayList: array.add(new Person("Horatio", 1835,12,6)); array.add(new Person("Charles",1897,3,11)); array.add(new Person("Albert",1901,1,20)); test(array); array.add(new Person("James", 1976, 8, 13)); // Build LinkedList: LinkedList list = new LinkedList(array); List view = list.subList(1,3); view.add(new Person("Gregory", 1582, 10, 15)); Collections.reverse(view); test(list); } }

View is defined as containing the second and third elements of list (i.e., indexes 1 and 2), where list is itself a copy of array.

Since view is just a wrapper for a subset of list, any operations on view affect list. Appending Gregory's instance to view, therefore, inserts it after James, not Charles, the latter being outside of view.

There are more algorithms in Collections. Some of the algorithms contain the prefixes unmodifiable and synchronized. These methods act as wrappers for existing collections and restrict their use.

class Modify { public static void main(String[] args) { ArrayList a = new ArrayList(); a.add(new Integer(1)); a.add(new Integer(2)); a.add(new Integer(3)); System.out.println(a); // Modify via iterator: ListIterator p = (ListIterator) a.listIterator(); while (p.hasNext()) { Integer i = (Integer) p.next(); p.set(new Integer(i.intValue() + 1)); } System.out.println(a); } } /* Output: [1, 2, 3] [2, 3, 4] */

Sets

The Set interface conforms to the usual notion of a mathematical set, which basically is just an unordered receptacle for elements, and provides operations for insertion, removal, and testing of membership.

Since these are already part of the Collections interface, the Set interface is identical to Collection, with the added specification that duplicates are not allowed.

The SortedSet interface adds methods useful for processing a set ordered by comparator.

Interface SortedSet extends Set { Comparator comparator(); Object first(); SortedSet headSet(Object toElement); Object last(); SortedSet subSet(Object fromElement, Object toElement); SortedSet tailSet(Object fromElement); }

The HashSet class implements Set, and TreeSet implements SortedSet.

HashSets are more efficient, since they use hashing algorithms; but if order is important, TreeSets at least provide logarithmic-time algorithms, since they store objects in balanced tree structures.

Ay attempts to insert duplicates into a set are ignored.

class SetTest { public static void test(Set x) { // Do a search: Person p = new Person("Albert",1901,1,20); if (x.contains(p)) System.out.println("Found " + p); System.out.println("max == " + Collections.max(x)); System.out.println("min == " + Collections.min(x)); iterate(x); public static void iterate(Collection c) { System.out.println("Iterating..."); Iterator i = c.iterator(); while (i.hasNext()) System.out.println(i.next()); } public static void main(String[] args) { // Build HashSet: HashSet h = new HashSet(); h.add(new Person("Horatio", 1835,12,6)); h.add(new Person("Charles",1897,3,11)); h.add(new Person("Albert",1901,1,20)); // The following is ignored: h.add(new Person("Albert",1901,1,20)); System.out.println(h); test(h); System.out.println(); // Build TreeSet: TreeSet t = new TreeSet(Collections.reverseOrder()); t.addAll(h); System.out.println(t); test(t); // Extra TreeSet stuff: boolean ctest = t.comparator().equals(Collections.reverseOrder()); System.out.println("Comparator test: " + ctest); System.out.println("first = " + t.first()); System.out.println("last = " + t.last()); Person p = new Person("Charles",1897,3,11); System.out.println(" headSet : " + t.headSet(p));System.out.println("tailSet: " + t. tailSet (p)); } }

For TreeSets, headSet returns a view from the beginning up to but not including the specified element and tailSet comprises the rest of the sequence.

The key methods of the Map interface are put and get. The put method stores a pair of objects in the map, and get retrieves the value for the given key.

If you want to just see the keys, keySet returns them as a Set view, and the values method returns the values as a Collection.

If you want to iterate through the pairs, you can call entrySet , which returns the pairs as a Set of instances of Map.EntrySet.

class MapTest { public static void main(String[] args) { HashMap h = new HashMap(); h.put("Alabama", "Montgomery"); h.put("Tennesee", "Nashville"); h.put("Georgia", "Atlanta"); // Alabama is a key, Montgomery is a value // The following is ignored: h.put("Georgia", "Atlanta"); test(h); TreeMap t = new TreeMap(Collections.reverseOrder()); t.putAll(h); test(t); // Extra TreeMap Stuff: boolean ctest = t.comparator().equals(Collections.reverseOrder()); System.out.println("Comparator test: " + ctest); System.out.println("firstKey = " + t.firstKey()); System.out.println("lastKey = " + t.lastKey()); System.out.println("headMap: " + t.headMap("Georgia")); System.out.println("tailMap: " + t.tailMap("Georgia")); } public static void test(Map m) { if (m.containsKey("Alabama")) System.out.println("Alabama is a key"); if (m.containsValue("Montgomery")) System.out.println("Montgomery is a value"); System.out.println("m[Georgia] = " + m.get("Georgia")); System.out.println("m[Michigan] = " + m.get("Michigan")); System.out.println("Keys: " + m.keySet()); System.out.println("Values: " + m.values()); iterate(m); } public static void iterate(Map m) { Set s = m.entrySet(); Iterator i = s.iterator(); while (i.hasNext()) { Map.Entry e = (Map.Entry)(i.next()); System.out.println(e); } } }

Note that calling put a second time with the same key replaces its associated value.

Application: a typical cross-reference lister, which prints each word from a text file with the line numbers where it appears. Applying this program to itself yields: a: 2, 28 Add: 45, 68 addLast: 69 already: 49 and: 45 args: 95, 98, 107, 114, 115 at: 28 boolean: 51 BufferedReader: 21, 102, 116 (etc.)

This program uses a Map that associates a token with a list of line numbers.

To make tokens appear in alphabetical order, it uses a TreeMap with the default comparator.

To ignore case in comparisons: define a comparator, called NoCase , that calls String.compareToIgnoreCase.

Before inserting a new pair, check to see if it is already in the map. If not, insert it with the statement: map.put(token, new LinkedList());

Retrieve the list of lines with LinkedList lines = (LinkedList) map.get(token);

Then check to see if the current line number has already been added to the list; if not, append it.

It would have been simpler to just use a TreeSet , but the constant re-balancing of the tree would degrade performance, and since the lines are entered in the correct order, a list suffices.

A call to entrySet returns the pairs as a Set of instances of Map.EntrySet.