Class 5: Notes

Collection Classes

Because of static typing, there is no simple List datatype in Java. Collection types specify the type of their elements by using type parameters. This feature was added to Java 1.5, so is not used in the textbook. Instead, they use the awkward object collection types like Vector and need to use run-time casts to the actual object type. You should not use Vector or any non-type safe collection type in your code for cs2220.

The Java API provides some useful collection classes that have parameterized types:

  • java.util.ArrayList<E> — similar to Scheme list or Python list
  • java.util.TreeSet<E> — a set datatype (don’t be confused by the Tree in the datatype name; it provides a set abstraction, the Tree is there to describe the implementation, but should not be part of the public interface of the datatype)
  • java.util.HashMap<K, V> — similar to Python Dictionary type. There are two type parameters: the key type (which must be immutable), and the value type (which can be any object type).

HashMap Example

import java.util.HashMap;
import java.util.Set;

/**
 * TallyTable provides an abstraction that maps a String to an integer value.
 * Initially, the count associated with every string is 0.
 */

public class TallyTable {

	private HashMap map;

	/**
	 * EFFECTS: Constructs a new, empty TallyTable.
	 */
	public TallyTable() {
		map = new HashMap();
	}

	/**
	 * Adds a word to the tally.
	 * MODIFIES: this
	 * EFFECTS: Increases the count associated with w by 1.
	 */
	public void tally(String w) {
		map.put(w, getTally(w) + 1);
	}

	/**
	 * Returns the count associated with w.
	 * EFFECTS: Returns the count associated with w.
	 * @param w
	 * @return the number of times w has been tally-ed.
	 */
	public int getTally(String w) {
		if (map.containsKey(w)) {
			return map.get(w);
		} else{
			return 0;
		}
	}

        ...
}

Validation

How can we increase our confidence that a program works as intended?

For what kinds of programs is exhaustive testing possible?

What is a successful test case?

What is the difference between testing and analysis?

What are the advantages and disadvantages of spending time on analysis instead of testing?

Comments are closed.