Return to lecture notes index

15-100 Lecture 23 (Friday, March 21, 2008)

Today's Challenge

Our goal today is to explore another type of operation on a container, ordered, or otherwise. We want to filter the container, returning a new container of only those items satisfying some criteria. In the process we want to leave the original container unchanged.

This type of method can be implemented on ether an ordered or unordered container. On your final exam, you'll be doing filtering upon an unordered container. Since we've most recently be developing an OrderedContainer, we'll work with that class today.

Our goal is to return a new OrderedContainer that contains all items from this container that are strictly less than the item passed in. So, we know that our signature must be as follows:

The greaterThan(...) Method

Our goal is to return a new OrderedContainer that contains all items from this container that are strictly greater than the item passed in. So, we know that our signature must be as follows:

public OrderedContainer greaterThan (Comparable item)

We know that we need to return a container -- so we must create one. Now, we're here:

public OrderedContainer greaterThan (Comparable item) {
  OrderedContainer newContainer = new OrderedContainer();

  ...

  return newContainer;
}

Now, we need to traverse the original OrderedContainer, adding everything that satisifies the criteria to the newContainer:

public OrderedContainer greaterThan (Comparable item) {
  OrderedContainer newContainer = new OrderedContainer();

  for (int index=0; index < nextSlot; index++) {
    if (list[index].compareTo(item) > 0)
      newContainer.add (list[index]);
  }
}

The solution above is correct, but not particularly efficient. It skips past the entire beginning just to get to the end. So, why not work from the end toward the beginning? Here's an improved version:

public OrderedContainer greaterThan (Comparable item) {
  OrderedContainer newContainer = new OrderedContainer();

  for (int index=(nextSlot-1); index >= 0; index--) {
    if (list[index].compareTo(item) > 0)
      newContainer.add (list[index]);
  }
}