The Collection interface from our textbook.
Notice that errors and exceptional conditions are handled differently than they were in the Stack and Queue classes. The add method doesn't throw an exception if the Collection is full; instead it returns false to indicate that the object wasn't added. Similarly, the contains method returns true if the object is in the Collection and false if not. The get method returns a matching object, or null if no matching object is found.
So now we have seen three ways to handle the "my data structure is full" condition:
We have the same options for handling problems in deleting (the data structure is empty or the object to be deleted is not found) and searching (the object is not found).
Some comments on the array implementation:
Here is the ArrayCollection class.
Suppose we have
ArrayCollection<String> myStrings = new ArrayCollection();
Draw the collection (the fields elements and numElements) after each of the following, and show any return value or output:
myStrings.add("true"); myStrings.add("blue"); myStrings.add("yes"); myStrings.add("green"); myStrings.add("sun"); myStrings.add("snow"); String str = myStrings.get("blue"); str = myStrings.get("red"); myStrings.remove("blue"); myStrings.remove("green");
Look at the code for the ArrayCollection methods. For a Collection containing N elements, what is the best case and worst case of each of the following? Count the number of times each statement executes as a function of N, then get the big O.
add
remove
contains
get
isFull
isEmpty
size
Some comments on the linked implementation:
previous = location; location = location.getLink();Thus previous always points to the node before location. When the item to be removed is found, previous points to the node before.
Here is the LinkedCollection class.
Look at the code for the LinkedCollection methods. For a Collection containing N elements, what is the best case and worst case of each of the following? Count the number of times each statement executes as a function of N, then get the big O.
add
remove
contains
get
isFull
isEmpty
size
The book presents two other collection classes, Bags and Sets.
You will see different definitions of a Bag in different references. Remember that the Collection allows duplicate elements. In our textbook, a Bag is a Collection with the following additional methods:
A set is a mathematical object: a collection of distinct elements. That means no duplicates. The fundamental operations on mathematical sets are intersection and union. Many Set data structures provide these operations. The Set data structure in our book does not. The only difference between the Set and the Collection is that no duplicate elements are allowed. This means that the Set class needs a different add method.
Email Me |
Office Hours |
My Home Page |
Department Home |
MCC Home Page
© Copyright Emmi Schatz 2017