Question

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 = INITIAL_CAPACITY;
       theData = (E[]) new Object[capacity];
   }  
  
   // A constructor for class KWArrayList<E> that accepts an integer argument
   // that represents the initial array capacity.
   @SuppressWarnings("unchecked")
   public KWArrayList(int num) {
       capacity = num;
       theData = (E[]) new Object[capacity];
   }      
  
   //Appends an item to the end of a KWArrayList
   public boolean add(E anEntry) {
       if (size == capacity) {
           reallocate();
       }
       theData[size] = anEntry;
       size++;
       return true;
   }
  
   // Insert an item at a specified position of index, i.e., theData[index]
   // Need to shift data in elements from index to size - 1
   public void add(int index, E anEntry) {
       if (index < 0 || index > size) {
           throw new ArrayIndexOutOfBoundsException(index);
       }
       if (size == capacity) {
           reallocate();
       }
       // Shift data in elements from index to size â€� 1
       for (int i = size; i > index; i--) {
           theData[i] = theData[i - 1];
       }
  
       // Insert the new item.
       theData[index] = anEntry;
       size++;
   }  
  
   public E get(int index) {
       if (index < 0 || index >= size) {
           throw new ArrayIndexOutOfBoundsException(index);
       }
       return theData[index];
   }
  
   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;
   }  
  
   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;
   }
  
   // Double the capacity of the array list
   private void reallocate() {
       capacity = 2 * capacity;
       theData = Arrays.copyOf(theData, capacity);
   }  
  
   // Get the size of the array list
   public int getSize() {
       return size;
   }
  
   // Get the capacity of the array list
   public int getCapacity() {
       return capacity;
   }  

public int indexOf(E value) {
       for(int index =0; index < size; index++) {
           if(value.equals(theData[index])) {
               return index;
           }
       }
       return -1;
   }  

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

I need help implementing the following method:

2(b).
//   int remove(E value)
//   Searches for value and remove the item (that is equal to the value) of the
//   first occurrence and return the item's index,
//   or return -1 if cannot find an item that is equal to the value in the arrayList
//   Hint: you can use two methods in the KWArrayList class to complete the
//   removing and index returning operations described in the remove(E value) method
   public int remove(E value) {
      
       return -1;
   }
}      

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Explanation:

Code in JAVA is given below

Output is given at the end

Code in JAVA:

KWArrayList.java 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 = INITIAL_CAPACITY;

theData = (E[]) new Object[capacity];

}  

// A constructor for class KWArrayList<E> that accepts an integer argument

// that represents the initial array capacity.

@SuppressWarnings("unchecked")

public KWArrayList(int num) {

capacity = num;

theData = (E[]) new Object[capacity];

}   

//Appends an item to the end of a KWArrayList

public boolean add(E anEntry) {

if (size == capacity) {

reallocate();

}

theData[size] = anEntry;

size++;

return true;

}

// Insert an item at a specified position of index, i.e., theData[index]

// Need to shift data in elements from index to size - 1

public void add(int index, E anEntry) {

if (index < 0 || index > size) {

throw new ArrayIndexOutOfBoundsException(index);

}

if (size == capacity) {

reallocate();

}

// Shift data in elements from index to size 1

for (int i = size; i > index; i--) {

theData[i] = theData[i - 1];

}

// Insert the new item.

theData[index] = anEntry;

size++;

}  

public E get(int index) {

if (index < 0 || index >= size) {

throw new ArrayIndexOutOfBoundsException(index);

}

return theData[index];

}

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;

}  

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;

}

// Double the capacity of the array list

private void reallocate() {

capacity = 2 * capacity;

theData = Arrays.copyOf(theData, capacity);

}  

// Get the size of the array list

public int getSize() {

return size;

}

// Get the capacity of the array list

public int getCapacity() {

return capacity;

}  

public int indexOf(E value) {

for(int index =0; index < size; index++) {

if(value.equals(theData[index])) {

return index;

}

}

return -1;

}  

/*I need help implementing the following method:

2(b).

// int remove(E value)

// Searches for value and remove the item (that is equal to the value) of the

// first occurrence and return the item's index,

// or return -1 if cannot find an item that is equal to the value in the arrayList

// Hint: you can use two methods in the KWArrayList class to complete the

// removing and index returning operations described in the remove(E value) method*/

public int remove(E value) {

int index = this.indexOf(value);

if(index==-1){

return -1;

}

value = this.remove(index);

return index;

}

}

KWTester.java Code:

public class KWTester {

public static void main(String[] args) {

KWArrayList<Integer> myList = new KWArrayList<Integer>(5);

myList.add(12);

myList.add(9);

myList.add(78);

myList.add(0, 89);

myList.add(23);

myList.add(111);

System.out.println("Current List:");

for(int i=0;i<myList.getSize();i++){

System.out.print(myList.get(i)+" ");

}

System.out.println();

System.out.println("\nTrying to remove value 89.");

Integer v = new Integer(89);

int index = myList.remove(v);

System.out.println("\nAfter removal of 89 List:");

for(int i=0;i<myList.getSize();i++){

System.out.print(myList.get(i)+" ");

}

}

}

OUTPUT:

Current List:

89 12 9 78 23 111

Trying to remove value 89.

After removal of 89 List:

12 9 78 23 111

Please provide the feedback!!

Thank You!

Add a comment
Know the answer?
Add Answer to:
Java Programming: The following is my code: import java.util.Arrays; public class KWArrayList<E> {    // Data...
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
  • 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...

  • 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...

  • JAVA // TO DO: add your implementation and JavaDoc public class SmartArray<T>{    private static final...

    JAVA // TO DO: add your implementation and JavaDoc public class SmartArray<T>{    private static final int DEFAULT_CAPACITY = 2;   //default initial capacity / minimum capacity    private T[] data;   //underlying array    // ADD MORE PRIVATE MEMBERS HERE IF NEEDED!       @SuppressWarnings("unchecked")    public SmartArray(){        //constructor        //initial capacity of the array should be DEFAULT_CAPACITY    }    @SuppressWarnings("unchecked")    public SmartArray(int initialCapacity){        // constructor        // set the initial capacity of...

  • 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...

  • Array with Iterator. Java style Implement an array data structure as a class JstyArray<E> to support...

    Array with Iterator. Java style Implement an array data structure as a class JstyArray<E> to support the Iterable interface such that the following code works: JstyArray<Integer> data; data = new JstyArray<Integer>(10); for (int i = 0; i < 10; ++i) { data.set(i, new Integer(i) ); } int sum = 0; for ( int v : data ) { if (v == null) continue; // empty cell sum += v; } The iterator provided by this class follows the behaviour of...

  • // 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...

  • 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...

  • JAVA Lab Create a class called ArrayBasedStack. Declare the following variables: • data: references an array...

    JAVA Lab Create a class called ArrayBasedStack. Declare the following variables: • data: references an array storing elements in the list • topOfStack: an int value representing the location of the stack top in the array • INITIAL_CAPACITY: the default capacity of the stack public class ArrayBasedStack <E> { private E[] data; private int topOfStack; private static final int INITIAL_CAPACITY = 5; } Add a constructor that will initialize the stack with a user-defined initial capacity. The top of the...

  • 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...

  • Expected OUTPUT: Codes Failed at Test D,E,F. Needs to be fixed: public class Vector<T> { private...

    Expected OUTPUT: Codes Failed at Test D,E,F. Needs to be fixed: public class Vector<T> { private const int DEFAULT_CAPACITY = 10; private T[] data; public int Count { get; private set; } = 0; public int Capacity { get { return data.Length; } }    public Vector(int capacity) { data = new T[capacity]; }    public Vector() : this(DEFAULT_CAPACITY) { } public T this[int index] { get { if (index >= Count || index < 0) throw new IndexOutOfRangeException(); return...

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