Question

I hope someone can explain this exercise to me. Thanks +++++++++++++ Programming Exercise Try to think...

I hope someone can explain this exercise to me. Thanks

+++++++++++++

Programming Exercise

Try to think about how to implement KWArrayList class. Please implement the following constructor and methods:

public KWArrayList()

public boolean add(E anEntry)

public E get(int index) {
public E set(int index, E newValue)
public E remove(int index)
private void reallocate()
public int size()
public int indexOf(Object item)

     

Study the code for ArrayList implementation (enclosed in the folder) and work on the following exercise

Provide a constructor for class KWArrayList<E> that accepts an int argument that represents the initial array capacity. Use this instead of INITIAL_CAPACITY.

2. Implement the indexOf method of the KWArrayList<E> class.

3.Write statements to remove the middle object from a KWArrayList and place it at the end.

/**

   Removes middle object and re-inserts it at the end

   @return E object removed and re-inserted

*/

public E removeMiddleInsertEnd()

{

}

4. Please define a tester class to verify your code.

import java.util.Arrays;
import java.util.AbstractList;

/**
 * This class implements some of the methods of the Java
 *  ArrayList class.
 *  @author Your Name
 */
public class KWArrayList extends AbstractList
        
{
    // Data Fields

    /** The default initial capacity */
    private static final int INITIAL_CAPACITY = 10;
    /** The underlying data array */
    private E[] theData;
    /** The current size */
    private int size = 0;
    /** The current capacity */
    private int capacity = 0;

    /**
     * Construct an empty KWArrayList with the default
     * initial capacity
     */
    public KWArrayList() {
        capacity = INITIAL_CAPACITY;
        theData = (E[]) new Object[capacity];
    }

    /*Your programming exercise 1 goes here*/
    /**
     * Construct an empty KWArrayList with a specified initial capacity
     * @param capacity The initial capacity  
     */
    
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    /**/


         
         /**
     * Appends the specified element to the end of this list.
     * 
     * @param theEntry - The value to be inserted
     * @throws ArrayIndexOUtOfBoundsException if index is
     *         less than zero or greater than size
     */ 
    public boolean add(E anEntry) {
        if (size == capacity) {
            reallocate();
        }
        theData[size] = anEntry;
        size++;
        return true;
    }

    /**
     * Get a value in the array based on its index.
     * @param index - The index of the item desired
     * @return The contents of the array at that index
     * @throws ArrayIndexOutOfBoundsException - if the index
     *         is negative or if it is greater than or equal to the
     *         current size
     */
    public E get(int index) {
        if (index < 0 || index >= size) {
            throw new ArrayIndexOutOfBoundsException(index);
        }
        return theData[index];
    }

    /**
     * Set the value in the array based on its index.
     * @param index - The index of the item desired
     * @param newValue - The new value to store at this position
     * @return The old value at this position
     * @throws ArrayIndexOutOfBoundsException - if the index
     *         is negative or if it is greater than or equal to the
     *         current size
     */
    public E set(int index, E newValue) {
        if (index < 0 || index >= size) {
            throw new ArrayIndexOutOfBoundsException(index);
        }
        E oldValue = theData[index];
        theData[index] = newValue;
        return oldValue;
    }

    /**
     * Remove an entry based on its index
     * @param index - The index of the entry to be removed
     * @return The value removed
     * @throws ArrayIndexOutOfBoundsException - if the index
     *         is negative or if it is greater than or equal to the
     *         current size
     */
    public E remove(int index) {
        if (index < 0 || index >= size) {
            throw new ArrayIndexOutOfBoundsException(index);
        }
        E returnValue = theData[index];
        for (int i = index + 1; i < size; i++) {
            theData[i - 1] = theData[i];
        }
        size--;
        return returnValue;
    }
        
        
        
        /*Your programming exercise 3 goes here*/
        /**
                Removes middle object and re-inserts it at the end 
                @return E object removed and re-inserted
        */
        public E removeMiddleInsertEnd()
        {

        
        
        
        
        
        
        
        

        
        
        
        } 


    /**
     * Allocate a new array to hold the directory
     */
    private void reallocate() {
        capacity = 2 * capacity;
        theData = Arrays.copyOf(theData, capacity);
    }

    /**
     * Get the current size of the array
     * @return The current size of the array
     */
    public int size() {
        return size;
    }

    /*Your programming exercise 2 goes here*/
    /**
     * Returns the index of the first occurence of the specified element
     * in this list, or -1 if this list does not contain the element
     * @param item The object to search for
     * @returns The index of the first occurence of the specified item
     *          or -1 if this list does not contain the element
     */
    public int indexOf(Object item) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
    }
    /**/
}
/**/
0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.util.Arrays;
import java.util.AbstractList;

/**
* This class implements some of the methods of the Java
* ArrayList class.
* @author Your Name
* @param <E>
*/
public class KWArrayList<E> extends AbstractList
      
{
    // Data Fields

    /** The default initial capacity */
    private static final int INITIAL_CAPACITY = 10;
    /** The underlying data array */
    private E[] theData;
    /** The current size */
    private int size = 0;
    /** The current capacity */
    private int capacity = 0;

    /**
     * Construct an empty KWArrayList with the default
     * initial capacity
     */
    public KWArrayList() {
        capacity = INITIAL_CAPACITY;
        theData = (E[]) new Object[capacity];
    }

    /*Your programming exercise 1 goes here*/
    /**
     * Construct an empty KWArrayList with a specified initial capacity
     * @param capacity The initial capacity
     */
   
    /**/


       
         /**
     * Appends the specified element to the end of this list.
     *
     * @param theEntry - The value to be inserted
     * @throws ArrayIndexOUtOfBoundsException if index is
     *         less than zero or greater than size
     */
    public boolean add(Object anEntry) {
        if (size == capacity) {
            reallocate();
        }
        theData[size] = (E) anEntry;
        size++;
        return true;
    }

    /**
     * Get a value in the array based on its index.
     * @param index - The index of the item desired
     * @return The contents of the array at that index
     * @throws ArrayIndexOutOfBoundsException - if the index
     *         is negative or if it is greater than or equal to the
     *         current size
     */
    public E get(int index) {
        if (index < 0 || index >= size) {
            throw new ArrayIndexOutOfBoundsException(index);
        }
        return theData[index];
    }

    /**
     * Set the value in the array based on its index.
     * @param index - The index of the item desired
     * @param newValue - The new value to store at this position
     * @return The old value at this position
     * @throws ArrayIndexOutOfBoundsException - if the index
     *         is negative or if it is greater than or equal to the
     *         current size
     */
    public E set(int index, Object newValue) {
        if (index < 0 || index >= size) {
            throw new ArrayIndexOutOfBoundsException(index);
        }
        E oldValue = theData[index];
        theData[index] = (E) newValue;
        return oldValue;
    }

    /**
     * Remove an entry based on its index
     * @param index - The index of the entry to be removed
     * @return The value removed
     * @throws ArrayIndexOutOfBoundsException - if the index
     *         is negative or if it is greater than or equal to the
     *         current size
     */
    public E remove(int index) {
        if (index < 0 || index >= size) {
            throw new ArrayIndexOutOfBoundsException(index);
        }
        E returnValue = theData[index];
        for (int i = index + 1; i < size; i++) {
            theData[i - 1] = theData[i];
        }
        size--;
        return returnValue;
    }
      
      
      
        /*Your programming exercise 3 goes here*/
        /**
                Removes middle object and re-inserts it at the end
                @return E object removed and re-inserted
        */
        public E removeMiddleInsertEnd()
        {

      
         int middle = size/2;
           E element = remove(middle);
          
           add(element);
          
          
           return element;
      
      
      
               
        }


    /**
     * Allocate a new array to hold the directory
     */
    private void reallocate() {
        capacity = 2 * capacity;
        theData = Arrays.copyOf(theData, capacity);
    }

    /**
     * Get the current size of the array
     * @return The current size of the array
     */
    public int size() {
        return size;
    }

    /*Your programming exercise 2 goes here*/
    /**
     * Returns the index of the first occurence of the specified element
     * in this list, or -1 if this list does not contain the element
     * @param item The object to search for
     * @returns The index of the first occurence of the specified item
     *          or -1 if this list does not contain the element
     */
    public int indexOf(Object item) {
       for (int i = 0; i < size; ++i) {
           if (item.equals(theData[i]))
               return i;
       }
       return -1;
    }
    /**/
}
/**/

=========================================================================================

4)


public class KWArrayListTest {
  
public static void main(String args[]){
      
       KWArrayList myArrayList = new KWArrayList();
       System.out.println("Size of array is: " + myArrayList.size() );
       myArrayList.add(1);
       myArrayList.add(10);
       myArrayList.add(21);
       myArrayList.add(100);
       myArrayList.add(101);
       System.out.println("Size of array is: " + myArrayList.size() );
  
       for(int i=0;i<myArrayList.size();++i){
           System.out.print(myArrayList.get(i) + " ");
       }
      
       System.out.println("\nremoveMiddleInsertEnd: " + myArrayList.removeMiddleInsertEnd() );
       for(int i=0;i<myArrayList.size();++i){
           System.out.print(myArrayList.get(i) + " ");
       }
      
   }

}

===========================================================================

See Output


Thanks

Add a comment
Know the answer?
Add Answer to:
I hope someone can explain this exercise to me. Thanks +++++++++++++ Programming Exercise Try to think...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Java Programming: The following is my code: import java.util.Arrays; public class KWArrayList<E> {    // Data...

    Java Programming: The following is my code: import java.util.Arrays; public class KWArrayList<E> {    // Data fields    /** The default initial capacity */    private static final int INITIAL_CAPACITY = 10;       /** The underlying data array */    private E[] theData;       /** The current size */    private int size = 0;       /** The current capacity */    private int capacity = 0;       @SuppressWarnings("unchecked")    public KWArrayList() {        capacity...

  • Java Programming: The following is my code: public class KWSingleLinkedList<E> {    public void setSize(int size)...

    Java Programming: The following is my code: public class KWSingleLinkedList<E> {    public void setSize(int size)    {        this.size = size;    }    /** Reference to list head. */    private Node<E> head = null;    /** The number of items in the list */    private int size = 0;       /** Add an item to the front of the list.    @param item The item to be added    */    public void addFirst(E...

  • Load to the IDEA the remaining classes from the provided Lab02.zip file. Repeat the previous project...

    Load to the IDEA the remaining classes from the provided Lab02.zip file. Repeat the previous project inside the ArraySetWithArray class. As shown in the UML diagram below ArraySetWithArray class does not utilize ResizableArrayBag object as its instance variable, it has setOfEntries defined as an array which should be dynamically resized if more room needed (double the size). displaySet method should check if the set is empty and display appropriate message; if the set is not empty should display the number...

  • // I need help with the following questions. Please use java programming ECLIPSE language to solve...

    // I need help with the following questions. Please use java programming ECLIPSE language to solve the questions. YOU ONLY NEED TO DIRECTLY COPY IT IN YOUR ECLIPSE APPLICATION AND RUN IT. I NEED THOSE PART WHICH IS SAYS --> "TO BE COMPLETED" I NEED HELP WITH [GET*] AND [REPLACE ALL] AND [ADD INT DOUBLE] PLEASE. import java.util.ArrayList; public class CustomArrayList { //instance variables public int[] data; //data.length gives the capacity public int nItems; //nItems gives items currently in the...

  • Java Write an intersection method for the ResizableArrayBag class. The intersection of two bags is the...

    Java Write an intersection method for the ResizableArrayBag class. The intersection of two bags is the overlapping content of the bags. Intersections are explained in more detail in Chapter 1, #6. An intersecion might contain duplicates. The method should not alter either bag. The current bag and the bag sent in as a parameter should be the same when the method ends. The method header is: public BagInterface<T> intersection(ResizableArrayBag <T> anotherBag) Example: bag1 contains (1, 2, 2, 3) bag2 contains...

  • Suppose that you have several numbered billiard balls on a pool table. The smallest possible number...

    Suppose that you have several numbered billiard balls on a pool table. The smallest possible number on the ball is “1”. At each step, you remove a billiard ball from the table. If the ball removed is numbered n, you replace it with n balls randomly numbered less than n. For example, if you remove the “5” ball, you replace it with balls numbered “2”, “1”, “1”, “4”, and “3”, where numbers 2, 1, 1, 4, and 3 were randomly...

  • JAVA: Already completed: MyList.java, MyAbstractList.java, MyArrayList.java, MyLinkedLink.java, MyStack.java, MyQueue.java. Need to complete: ReversePoem.java. This program has...

    JAVA: Already completed: MyList.java, MyAbstractList.java, MyArrayList.java, MyLinkedLink.java, MyStack.java, MyQueue.java. Need to complete: ReversePoem.java. This program has you display a pessimistic poem from a list of phrases. Next, this program has you reverse the phrases to find another more optimistic poem. Use the following algorithm. 1.   You are given a list of phrases each ending with a pound sign: ‘#’. 2.   Create a single String object from this list. 3.   Then, split the String of phrases into an array of phrases...

  • Java/Queues ** Task: Write a JUnit test that shows a failure in some part of the...

    Java/Queues ** Task: Write a JUnit test that shows a failure in some part of the ADT -----ArrayQueue.java------- public class ArrayQueue {    private static final int INITIAL_CAPACITY = 2; // to permit easier testing    private Object[] contents;    private int front, rear;       /**    * Create an empty queue with an initial capacity.    */    public ArrayQueue() {        contents = new Object[INITIAL_CAPACITY];    }       /**    * Add an element to...

  • JAVA - Circular Doubly Linked List Does anybody could help me with this method below(previous)? public...

    JAVA - Circular Doubly Linked List Does anybody could help me with this method below(previous)? public E previous() { // Returns the previous Element return null; } Explanation: We have this class with these two implemented inferfaces: The interfaces are: package edu.ics211.h04; /** * Interface for a List211. * * @author Cam Moore * @param the generic type of the Lists. */ public interface IList211 { /** * Gets the item at the given index. * @param index the index....

  • package model; import java.util.Iterator; /** * This class implements interface PriorityList<E> to represent a generic *...

    package model; import java.util.Iterator; /** * This class implements interface PriorityList<E> to represent a generic * collection to store elements where indexes represent priorities and the * priorities can change in several ways. * * This collection class uses an Object[] data structure to store elements. * * @param <E> The type of all elements stored in this collection */ // You will have an error until you have have all methods // specified in interface PriorityList included inside this...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT