return to lecture notes index

15-100 Lecture 32 (Monday, April 11, 2005)

ArrayLists - continued

Last friday we started using ArrayLists, and we're going to finish up with them today by doing a quick ArrayList example. Before we begin I want to start with a quick comment. Whenever using any of the predefined java classes, like ArrayList, one of the most helpful resourses that you'll be able to use is the java api. The java api lists all the predefined classes in java and the methods that they have. It can be incredibly useful when programming, because you can just go on the website and check if you are using a method correctly, or you can check through the available methods to see if there is a method that you didn't know about, but would be very useful for your application.

Now getting back to the ArrayLists. The example that we're going to do today is just a relatively simple example, we're going to create an ArrayList, add items to it, get items from it, remove items from it, and see if it contains a specific item.

Since most of this is self explainitory we'll just go ahead and write the code.


//You must import the package that the class you want to use is in
//You have to do this because all of java's predefined classes
//aren't compiled every time you compile a class.  Doing
//this tells java that when it compiles your class you also
//want it to use those other classes as well
import java.util.*; 
 
class ArrayListExample { 
 
  public static void main (String[] args) { 
 
    //creates your ArrayList, with a size of 100
    ArrayList al = new ArrayList(100); 
 
    //adds several elements to the ArrayList
    //while the elements that we're adding here are Strings
    //if you check the java api you can see that anything
    //that is an Object can be added to an ArrayList
    al.add ("Greg"); 
    al.add ("Mark"); 
    al.add ("Tom"); 
    al.add ("Jeff"); 
    al.add ("Jim"); 
    al.add ("Rich"); 
    al.add ("Tim"); 
 
    //prints the item at position 0 in the array
    System.out.println (al.get(0)); 

    //prints the item at position 6 in the array
    System.out.println (al.get(6)); 
 
   //finds the index of the element that is equalTo "Greg"
    System.out.println ("Greg is at position: " + al.indexOf("Greg"));

    //returns a boolean indicating whether or not there is an 
    //element equalTo "Jeff" in the array 
    System.out.println ("Jeff is a lecturer: " + al.contains("Jeff")); 
   
   //returns whether "Jim" is in the array
    System.out.println ("Jim is a lecturer: " + al.contains("Jim")); 
   
   //returns whether "Bonzo" is in the array
    System.out.println ("Bonzo is a lecturer: " + al.contains("Bonzo")); 
 
   //removes the item equal to the item "Jim" from the array
    al.remove("Jim"); 

    //returns whether "Jim" is in the array
    System.out.println ("Jim is a lecturer: " + al.contains("Jim")); 
  } 
} 
	  

Counted Collection

One of the seven mastery Exam paterns is the Counted Collection. Now the way that they set this up is not the way that you would ever actually do this class. The reason that they did it this way is because they wanted you to have to do certain things, and not all the classes have used interfaces and they only wanted to have two classes.

If you just think about classes in java you will also see why Counted Collections aren't the way to do. Just think of a collection of cars. What if this collection of cars was a countable collection. In that case if you created a "Ford Focus" then that class would have to keep track of all the "Ford Focuses" that exist. This doesn't make much sense though. If we want a Ford Focus then we probably don't usually care how many exist in the world, and it may not even be possible to find how many exist in the world. What we really want to do is to create a Ford Focus, and then if an application cares how many there are then a count of Ford Focuss can be kept outside of the class.

However, since the mastery exam has a countable class we will do a countable class.

The countable class that we'll do our example on we'll call the CountedCollection. Now, before we make our collection we need to make a class of Objects that our CountedCollection will hold. We'll call this class the LineItem.

Since we're making a CountedClass the most important feature of LineItem is that it should have a count of the number of that type of item. Other then that there's not much that we care about for our item, so lets go ahead and write our class.


  private class LineItem {
    private String item; //holds the name of the item

    //holds the number of this item that we have
    private int count;  

//if we're not provided with a count for this item 
//the default is 1
    private static final int DEFAULT_COUNT = 1;

  //Constructors
    public LineItem(String item, int count) {
      this.item = item;
      this.count = count;
    }

    public LineItem(Object item) {
      this.item = item;
      this.count = DEFAULT_COUNT;
    }

    //returns the count of this item
    public int getCount() {
      return count;
    }

   //increases count by the specified value
   public void changeCountBy (int change) {
     count += change;
   }
   
   //returns the name of the item
    public String  getName() {
      return item;
    }

   //returns the string representation of the item
    public String toString() {
      return "" + item + ": " + count;
    }

    //defines an equals methods for this object
    public boolean equals(Object o) {
      LineItem li = (LineItem) o;
      return item.equals(li.item);
    }
  }

	  

So now we have created out CountableClass, so now lets create a collection for it. And we'll have this collection have some of the same types of methods that the mastery exam will have.


class CountedCollection{
  private LineItem[] items; //the collection
  private int count; //number of items in the collection

  private static final int DEFAULT_SIZE = 100;
  private static final double GROUWTH_AMOUNT = 1.0;


  //Constructors
  public CountedCollection() {
    items = new LineItem[DEFAULT_SIZE];
    count = 0;
  }


  public CountedCollection(int size) {
    items = new LineItem[size];
    count = 0;
  }

  //increases the list size by a specified percentage
  private void grow() {

    LineItem[] biggerArray =
      new LineItem[(int) ((1.0+GROWTH_AMOUNT) * items.length)];

    for (int index=0; index < count; index++)
      biggerArray[index] = items[index];

    items = biggerArray;
  }

 //inserts the item at the end
  private void insert (LineItem item) {
    if (count == items.length)
      grow();

    items[count++] = item; // items[count] = item; count++;
  }

  public void add (Object item, int count) {

    for (int index=0; index < this.count; index++) {
      if (items[index].getItem().equals(item)) {
        items[index].changeCountBy(count);
        return;
      }
    }

    insert (new LineItem(item, count));
  }

//Removes the item at the given index
  private void removeItemAtIndex(int index) {
    for ( ; index < (count-1); index++) {
      items[index+1] = items[index];
    }

    count--;
    items[count] = null;
  }

//removes the first item equal to the item
//passed in
  public void remove (Object item, int count) {

    for (int index=0; index < count; index++) {
      if (items[index].getItem().equals(item)) {
        items[index].changeCountBy(-1*count);

        if (items[index].getCount() == 0)
          removeItemAtIndex (index);
          return;
      }
    }
  }

//returns the number of each item in the list
  public int getQuantity(Object item) {
    for (int index=0; index < count; index++) {
      if (items[index].getItem().equals(item)) {
          return items[index].getCount();
      }
    }

    return 0; // thrown an ItemNotFoundException ?
  }
}