Exercises

  1. (Collections) Here is the outline of a class that provides access to its data structure through an iterator. Write the iterator.

    class storage {

        private Object[] data = new Object[256];

        // don't allow access to anything not yet stored
        private int nextEmptySlot = 0;
        private int i=0;

        public Iterator iterator() {
           // returns a class that iterates over the data array
           return new Iterator() {
           // insert the body of the inner class here
           // 3 methods: remove(), hasNext(), next()
          };
        }
    }

  2. (Collections) Take the storage class from the previous question and add all the code necessary to make it implement the Collection interface. Make the type of the object stored a generic parameter. Limit the number of objects in the collection, and hence the size of the array to 128 elements. Throw an UnsupportedOperationException if someone tries to add element number 129.

  3. (Collections) Take the storage class from the previous question and remove any limit on the number of data items held in the collection. If you try to add an element when there is no more room in the array, then allocate a new, larger array, and use System.arraycopy() to fill it with the contents of the old array. Hint: Add the extra code in a subclass that overrides the methods of the parent class. That way, you simply inherit all the things that you do not need to change.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.86.211