Question

In: Computer Science

In Java: Complete the following methods in the template by adhering to the comments: // TO...

In Java:

Complete the following methods in the template by adhering to the comments:

// TO DO: add your implementation and JavaDoc

public class BetterArray<T> {
   private static final int DEFAULT_CAPACITY = 2; //default initial capacity / minimum capacity
   private T[] data;  //underlying array, you MUST use this for full credit

   // ADD MORE PRIVATE MEMBERS HERE IF NEEDED!

   @SuppressWarnings("unchecked")
   public BetterArray() {
      //constructor
      //initial capacity of the array should be DEFAULT_CAPACITY
   }

   @SuppressWarnings("unchecked")
   public BetterArray(int initialCapacity) {
      // constructor
      // set the initial capacity of the smart array as initialCapacity
      // throw IllegalArgumentException if initialCapacity is smaller than 1
   }


   public int size() {
      //report number of elements in the smart array
      // O(1)

      return -1;
   }

   public int capacity() {
      //report max number of elements before the next expansion
      // O(1)

      return -1;
   }

   @SuppressWarnings("unchecked")
   public boolean append(T value) {
      // add an element to the end   
      // return true  

      // double capacity if no space available
      // amortized O(1)

      return false;
   }

   @SuppressWarnings("unchecked")
   public void add(int index, T value) {
      // insert value at index, shift elements if needed  
      // double the capacity if no space is available
      // throw IndexOutOfBoundsException for invalid index
      // O(N) where N is the number of elements in the array

      // Note: this method may be used to append items as
      // well as insert items
   }

   public T get(int index){
      // return the item at index
      // throw IndexOutOfBoundsException for invalid index
      // O(1)

      return null;
   }

   public T replace(int index, T value){
      // change item at index to be value    
      // return old item at index
      // throw IndexOutOfBoundsException for invalid index
      // O(1)

      // Note: you cannot add new items with this method

      return null;
   }

   @SuppressWarnings("unchecked")
   public T delete(int index){
      // remove and return element at position index
      // shift elements to remove any gap in the array
      // throw IndexOutOfBoundsException for invalid index

      // halve capacity if the number of elements falls below 1/4 of the capacity
      // capacity should NOT go below DEFAULT_CAPACITY

      // O(N) where N is the number of elements in the list

      return null;
   }

   public int firstIndexOf(T value){
      // return the index of the first occurrence or -1 if not found
      // O(n)

      return -1;
   }

   @SuppressWarnings("unchecked")
   public boolean ensureCapacity(int newCapacity){
      // change the max number of items allowed before next expansion to newCapacity

      // capacity should not be changed if:
      //   - newCapacity is below DEFAULT_CAPACITY; or 
      //   - newCapacity is not large enough to accommodate current number of items

      // return true if newCapacity gets applied; false otherwise
      // O(N) where N is the number of elements in the array 

      return false;
   }

   public BetterArray<T> clone() {
      //make a copy of all the current values
      //don't forget to set the capacity!
      //O(n)

      return null;
   }


   // --------------------------------------------------------
   // example testing code... edit this as much as you want!
   // --------------------------------------------------------
   public static void main(String args[]) {
      //create a smart array of integers
      BetterArray<Integer> nums = new BetterArray<>();
      if ((nums.size() == 0) && (nums.capacity() == 2)){
         System.out.println("Yay 1");
      }

      //append some numbers 
      for (int i=0; i<3;i++)
         nums.add(i,i*2);

      if (nums.size()==3 && nums.get(2) == 4 && nums.capacity() == 4 ){
         System.out.println("Yay 2");
      }

      //create a smart array of strings
      BetterArray<String> msg = new BetterArray<>();

      //insert some strings
      msg.add(0,"world");
      msg.add(0,"hello");
      msg.add(1,"new");
      msg.append("!");

      //replace and checking
      if (msg.get(0).equals("hello") && msg.replace(1,"beautiful").equals("new")
            && msg.size() == 4 && msg.capacity() == 4 ){
         System.out.println("Yay 3");
      }

      //change capacity
      if (!msg.ensureCapacity(0) && !msg.ensureCapacity(3) && msg.ensureCapacity(20)
            && msg.capacity() == 20){
         System.out.println("Yay 4");
      }

      //delete and shrinking
      if (msg.delete(1).equals("beautiful") && msg.get(1).equals("world")
            && msg.size() == 3 && msg.capacity() == 10 ){
         System.out.println("Yay 5");
      }

      //firstIndexOf and clone
      //remember what == does on objects... not the same as .equals()
      BetterArray<String> msgClone = msg.clone();
      if (msgClone != msg && msgClone.get(1) == msg.get(1)
            && msgClone.size() == msg.size()
            && msgClone.capacity() == msg.capacity()
            && msgClone.firstIndexOf("world") == 1
            && msgClone.firstIndexOf("beautiful") == -1) {
         System.out.println("Yay 6");
      }
   }

   // --------------------------------------------------------
   // DO NOT EDIT ANYTHING BELOW THIS LINE (except to add JavaDocs)
   // --------------------------------------------------------

   public String toString() {
      if(size() == 0) return "";

      StringBuffer sb = new StringBuffer();
      sb.append(get(0));
      for(int i = 1; i < size(); i++) {
         sb.append(", ");
         sb.append(get(i));
      }
      return sb.toString();
   }
}

Solutions

Expert Solution

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

// BetterArray.java

public class BetterArray<T> {

      private static final int DEFAULT_CAPACITY = 2; // default initial capacity /

                                                                               // minimum capacity

      private T[] data; // underlying array, you MUST use this for full credit

      // number of elements

      private int size;

      /**

      * default constructor

      */

      @SuppressWarnings("unchecked")

      public BetterArray() {

            data = (T[]) new Object[DEFAULT_CAPACITY];

            size = 0;

      }

      /**

      * constructor taking initial capacity

      *

      * @param initialCapacity

      *            capacity >= 1, if less than 1, will throw

      *            IllegalArgumentException

      */

      @SuppressWarnings("unchecked")

      public BetterArray(int initialCapacity) {

            // constructor

            // set the initial capacity of the smart array as initialCapacity

            // throw IllegalArgumentException if initialCapacity is smaller than 1

            if (initialCapacity < 1) {

                  throw new IllegalArgumentException("Invalid capacity");

            }

            data = (T[]) new Object[initialCapacity];

            size = 0;

      }

      /**

      * getter for list size

      *

      * @return the size

      */

      public int size() {

            // report number of elements in the smart array

            // O(1)

            return size;

      }

      /**

      * report max number of elements before the next expansion

      *

      * @return the current capacity

      */

      public int capacity() {

            // report max number of elements before the next expansion

            // O(1)

            return data.length;

      }

      /**

      * adds an element to the end

      *

      * @param value

      *            value to be added

      * @return true if added, false if not

      */

      public boolean append(T value) {

            // resizing array to double capacity if full

            if (size == data.length) {

                  ensureCapacity(data.length * 2);

            }

            // adding to end

            data[size] = value;

            size++;

            return true;

      }

      /**

      * insert value at index

      *

      * @param index

      *            index value

      * @param value

      *            value to be added

      * @throws IndexOutOfBoundsException

      *             if index is invalid

      */

      public void add(int index, T value) {

            // insert value at index, shift elements if needed

            // double the capacity if no space is available

            // throw IndexOutOfBoundsException for invalid index

            // O(N) where N is the number of elements in the array

            // throwing exception if index is invalid

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

                  throw new IndexOutOfBoundsException("Invalid index");

            }

            // resizing array if necessary

            if (size == data.length) {

                  ensureCapacity(data.length * 2);

            }

            // shifting elements starting from index to one place right

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

                  data[i] = data[i - 1];

            }

            // adding element to index, and updating size

            data[index] = value;

            size++;

      }

      /**

      * return the item at index

      *

      * @param index

      *            index of element

      * @return the element at index

      * @throws IndexOutOfBoundsException

      *             if index is invalid

      */

      public T get(int index) {

            // throwing exception if index is invalid

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

                  throw new IndexOutOfBoundsException("Invalid index");

            }

            // return the item at index

            return data[index];

      }

      /**

      * replace an element at specified index with new one

      *

      * @param index

      *            index of element

      * @param value

      *            new value

      * @return old value

      * @throws IndexOutOfBoundsException

      *             if index is invalid

      */

      public T replace(int index, T value) {

            // throwing exception if index is invalid

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

                  throw new IndexOutOfBoundsException("Invalid index");

            }

            // storing old value

            T oldValue = data[index];

            // replacing with new value

            data[index] = value;

            // returning old value

            return oldValue;

      }

      /**

      * removes and returns element at an index

      *

      * @param index

      *            index of element to delete

      * @return deleted element

      */

      public T delete(int index) {

            // throwing exception if index is invalid

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

                  throw new IndexOutOfBoundsException("Invalid index");

            }

            // storing element to remove

            T element = data[index];

            // shifting all elements starting from index+1 position, to one place

            // left

            for (int i = index; i < size - 1; i++) {

                  data[i] = data[i + 1];

            }

            // updating size, returning removed element

            size--;

            // checking if size go below 1/4th of capacity

            if (size < (data.length / 4)) {

                  // finding new capacity (half)

                  int newCapacity = data.length / 2;

                  // if this new capacity is below default capacity, using default

                  // capacity

                  if (newCapacity < DEFAULT_CAPACITY) {

                        newCapacity = DEFAULT_CAPACITY;

                  }

                  // resizing array

                  ensureCapacity(newCapacity);

            }

            // returning removed element

            return element;

      }

      /**

      * returns the first index of an element

      *

      * @param value

      *            element

      * @return first index, -1 if not found

      */

      public int firstIndexOf(T value) {

            // looping through elements

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

                  if (data[i].equals(value)) {

                        return i; // found

                  }

            }

            return -1; // not found

      }

      /**

      * upsize or downsize the underlying array as needed

      *

      * @param newCapacity

      *            new capacity

      * @return true if resized, false if not

      */

      @SuppressWarnings("unchecked")

      public boolean ensureCapacity(int newCapacity) {

            // change the max number of items allowed before next expansion to

            // newCapacity

            // capacity should not be changed if:

            // - newCapacity is below DEFAULT_CAPACITY; or

            // - newCapacity is not large enough to accommodate current number of

            // items

            // return true if newCapacity gets applied; false otherwise

            // O(N) where N is the number of elements in the array

            // creating array of new size

            if (newCapacity < DEFAULT_CAPACITY || newCapacity < size) {

                  return false;

            }

            // creating new array with enough capacity

            T newArr[] = (T[]) new Object[newCapacity];

            // copying elements

            for (int i = 0; i < size && i < newCapacity; i++) {

                  newArr[i] = data[i];

            }

            // replacing old with new array

            data = newArr;

            return true;

      }

      /**

      * returns a BetterArray object, which is same as this object

      *

      * @return cloned BetterArray object with same capacity, elements

      */

      public BetterArray<T> clone() {

            // make a copy of all the current values

            // don't forget to set the capacity!

            // O(n)

            BetterArray<T> cloned = new BetterArray<T>(data.length);

            // copying all elements

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

                  cloned.data[i] = data[i];

            }

            // updating size

            cloned.size = size;

            return cloned;

      }

      // --------------------------------------------------------

      // example testing code... edit this as much as you want!

      // --------------------------------------------------------

      public static void main(String args[]) {

            // create a smart array of integers

            BetterArray<Integer> nums = new BetterArray<Integer>();

            if ((nums.size() == 0) && (nums.capacity() == 2)) {

                  System.out.println("Yay 1");

            }

            // append some numbers

            for (int i = 0; i < 3; i++)

                  nums.add(i, i * 2);

            if (nums.size() == 3 && nums.get(2) == 4 && nums.capacity() == 4) {

                  System.out.println("Yay 2");

            }

            // create a smart array of strings

            BetterArray<String> msg = new BetterArray<String>();

            // insert some strings

            msg.add(0, "world");

            msg.add(0, "hello");

            msg.add(1, "new");

            msg.append("!");

            // replace and checking

            if (msg.get(0).equals("hello")

                        && msg.replace(1, "beautiful").equals("new") && msg.size() == 4

                        && msg.capacity() == 4) {

                  System.out.println("Yay 3");

            }

            // change capacity

            if (!msg.ensureCapacity(0) && !msg.ensureCapacity(3)

                        && msg.ensureCapacity(20) && msg.capacity() == 20) {

                  System.out.println("Yay 4");

            }

            // delete and shrinking

            if (msg.delete(1).equals("beautiful") && msg.get(1).equals("world")

                        && msg.size() == 3 && msg.capacity() == 10) {

                  System.out.println("Yay 5");

            }

            // firstIndexOf and clone

            // remember what == does on objects... not the same as .equals()

            BetterArray<String> msgClone = msg.clone();

            if (msgClone != msg && msgClone.get(1) == msg.get(1)

                        && msgClone.size() == msg.size()

                        && msgClone.capacity() == msg.capacity()

                        && msgClone.firstIndexOf("world") == 1

                        && msgClone.firstIndexOf("beautiful") == -1) {

                  System.out.println("Yay 6");

            }

      }

      // --------------------------------------------------------

      // DO NOT EDIT ANYTHING BELOW THIS LINE (except to add JavaDocs)

      // --------------------------------------------------------

      public String toString() {

            if (size() == 0)

                  return "";

            StringBuffer sb = new StringBuffer();

            sb.append(get(0));

            for (int i = 1; i < size(); i++) {

                  sb.append(", ");

                  sb.append(get(i));

            }

            return sb.toString();

      }

}

/*OUTPUT*/

Yay 1

Yay 2

Yay 3

Yay 4

Yay 5

Yay 6


Related Solutions

Complete the following methods in java: Consult the rest of the methods of BigInteger from its...
Complete the following methods in java: Consult the rest of the methods of BigInteger from its API documentation as needed to solve the following problems. public static List<BigInteger> fibonacciSum(BigInteger n) The unique breakdown into Fibonacci numbers can be constructed with a greedy algorithm that simply finds the largest Fibonacci number f that is less than or equal to n. Add this f to the result list, and break down the rest of the number given by the expression n-f the...
Write a complete Java program, including comments in each method and in the main program, to...
Write a complete Java program, including comments in each method and in the main program, to do the following: Outline: The main program will read in a group of three integer values which represent a student's SAT scores. The main program will call a method to determine if these three scores are all valid--valid means in the range from 200 to 800, including both end points, and is a multiple of 10 (ends in a 0). If the scores are...
Write a complete Java program, including comments in each method and in the main program, to...
Write a complete Java program, including comments in each method and in the main program, to do the following: Outline: The main program will read in a group of three int||eger values which represent a student's SAT scores. The main program will call a method to determine if these three scores are all valid--valid means in the range from 200 to 800, including both end points, and is a multiple of 10 (ends in a 0). If the scores are...
complete this code for me, this is java question. // Some comments omitted for brevity import...
complete this code for me, this is java question. // Some comments omitted for brevity import java.util.*; /* * A class to demonstrate an ArrayList of Player objects */ public class ListOfPlayers { // an ArrayList of Player objects private ArrayList players; public ListOfPlayers() { // creates an empty ArrayList of Players players = new ArrayList<>(); } public void add3Players() { // adds 3 Player objects players.add(new Player("David", 10)); players.add(new Player("Susan", 5)); players.add(new Player("Jack", 25)); }    public void displayPlayers()...
Write a complete Java program, including comments in both the main program and in each method,...
Write a complete Java program, including comments in both the main program and in each method, which will do the following: 0. The main program starts by calling a method named introduction which prints out a description of what the program will do. This method is called just once.      This method is not sent any parameters, and it does not return a value. The method should print your name. Then it prints several lines of output explaining what the...
Write a complete Java program, including comments in both the main program and in each method,...
Write a complete Java program, including comments in both the main program and in each method, which will do the following: 0. The main program starts by calling a method named introduction which prints out a description of what the program will do. This method is called just once.      This method is not sent any parameters, and it does not return a value. The method should print your name. Then it prints several lines of output explaining what the...
Write a complete Java program, including comments in both the main program and in each method,...
Write a complete Java program, including comments in both the main program and in each method, which will do the following: 0. The main program starts by calling a method named introduction which prints out a description of what the program will do. This method is called just once.      This method is not sent any parameters, and it does not return a value. The method should print your name. Then it prints several lines of output explaining what the...
Write a complete JAVA program, including comments (worth 2 pts -- include a good comment at...
Write a complete JAVA program, including comments (worth 2 pts -- include a good comment at the top and at least one more good comment later in the program), to process data for the registrar as follows: NOTE: Include prompts. Send all output to the screen. 1. Read in the id number of a student, the number of credits the student has, and the student’s grade point average (this is a number like 3.25). Print the original data right after...
Methods – Compute Grade Please write a complete Java program, given the following information about (a...
Methods – Compute Grade Please write a complete Java program, given the following information about (a few lines of code in) main: projectAverage = getAverage(”Project”); // returns average of 2 grades testAverage = getAverage(”Test”); // returns average of 2 grades displayGrade(projectAverage, testAverage); // test are 70% & projects 30%
1. a) Write two algorithms of different time complexity implemented in Java methods in complete Java...
1. a) Write two algorithms of different time complexity implemented in Java methods in complete Java program to reverse a stack of characters. Make your own assumption and your own design on the methods signature, inputs, outputs, and the full main program.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT