Question

In: Computer Science

Create a file named StudentArrayList.java,within the file create a class named StudentArrayList. This class is meant...

Create a file named StudentArrayList.java,within the file create a class named StudentArrayList. This class is meant to mimic the ArrayList data structure. It will hold an ordered list of items. This list should have a variable size, meaning an arbitrary number of items may be added to the list. Most importantly this class should implement the interface SimpleArrayList provided. Feel free to add as many other functions and methods as needed to your class to accomplish this task. In other words, the class StudentArrayList must implement the interface SimpleArrayList. You have to write the code for each of the functions specified in the SimpleArrayList interface. Make sure the class that implements SimpleArrayList is named "StudentArrayList" or else the test code will not compile.

You are not allowed to use any 3rd party data structures or libraries such as Java.Utils.ArrayList or Java.awt.ArrayList.

Hints:

  • Make an object array (Object[]) as a field. Use the array to store elements added to the class. If an item is removed from the StudentArrayList all items to the left of the item that is removed must be shifted over one place to the left. When the array reaches capacity, you must augment the size of the object array by creating a larger empty array and copying elements from the old array into the new array.
  • Use .equals() to test the equality of elements in the Object array.
  • The size() function should return the total number of added items to the class not the total capacity of the internal array.

public interface SimpleArrayList<E> {

   /**
   * Returns the number of elements in this list. If this list contains more
   * than <tt>Integer.MAX_VALUE</tt> elements, returns
   * <tt>Integer.MAX_VALUE</tt>.
   *
   * @return the number of elements in this list
   */
   int size();

   /**
   * Returns <tt>true</tt> if this list contains no elements.
   *
   * @return <tt>true</tt> if this list contains no elements
   */
   boolean isEmpty();

   /**
   * Returns <tt>true</tt> if this list contains the specified element. More
   * formally, returns <tt>true</tt> if and only if this list contains at
   * least one element <tt>e</tt>
   *
   * @param o
   * element whose presence in this list is to be tested
   * @return <tt>true</tt> if this list contains the specified element
   */
   boolean contains(E o);

   /**
   * Returns an array containing all of the elements in this list in proper
   * sequence (from first to last element).
   *
   * <p>
   * The returned array will be "safe" in that no references to it are
   * maintained by this list. (In other words, this method must allocate a new
   * array even if this list is backed by an array). The caller is thus free
   * to modify the returned array.
   *
   * <p>
   * This method acts as bridge between array-based and student.SimpleArrayList-based
   * APIs.
   *
   * @return an array containing all of the elements in this list in proper
   * sequence
   */
   E[] toArray();

   /**
   * Appends the specified element to the end of this list
   *
   * @param e
   * element to be appended to this list
   */
   void add(E e);

   /**
   * Removes the first occurrence of the specified element from this list, if
   * it is present (optional operation). If this list does not contain the
   * element, it is unchanged.
   *
   * @param o
   * element to be removed from this list, if present
   */
   void remove(E o);

   /**
   * Returns <tt>true</tt> if this list contains all of the elements of the
   * specified student.SimpleArrayList.
   *
   * @param c
   * student.SimpleArrayList to be checked for containment in this list
   * @return <tt>true</tt> if this list contains all of the elements of the
   * specified student.SimpleArrayList
   */
   boolean containsAll(SimpleArrayList<E> c);

   /**
   * Appends all of the elements in the specified student.SimpleArrayList to the end
   * of this list, in the order that they are returned by the specified
   * student.SimpleArrayList.
   *
   * @param c
   * student.SimpleArrayList containing elements to be added to this list
   * @return <tt>true</tt> if this list changed as a result of the call
   */
   boolean addAll(SimpleArrayList<E> c);

   /**
   * Inserts all of the elements in the specified student.SimpleArrayList into this
   * list at the specified position. Shifts the element currently at that
   * position (if any) and any subsequent elements to the right (increases
   * their indices). The new elements will appear in this list in the order
   * that they are returned by the specified student.SimpleArrayList's iterator. The
   * behavior of this operation is undefined if the specified student.SimpleArrayList
   * is modified while the operation is in progress.
   *
   * @param index
   * index at which to insert the first element from the specified
   * student.SimpleArrayList
   * @param c
   * student.SimpleArrayList containing elements to be added to this list
   * @return <tt>true</tt> if this list changed as a result of the call
   */
   boolean addAll(int index, SimpleArrayList<E> c);

   /**
   * Removes from this list all of its elements that are contained in the
   * specified student.SimpleArrayList.
   *
   * @param c
   * student.SimpleArrayList containing elements to be removed from this
   * list
   * @return <tt>true</tt> if this list changed as a result of the call
   */
   boolean removeAll(SimpleArrayList<E> c);

   /**
   * Retains only the elements in this list that are contained in the
   * specified student.SimpleArrayList. In other words, removes from this list all of
   * its elements that are not contained in the specified student.SimpleArrayList.
   *
   * @param c
   * student.SimpleArrayList containing elements to be retained in this
   * list
   * @return <tt>true</tt> if this list changed as a result of the call
   */
   boolean retainAll(SimpleArrayList<E> c);

   /**
   * Removes all of the elements from this list (optional operation). The list
   * will be empty after this call returns.
   *
   */
   void clear();

   /**
   * Compares the specified object with this list for equality. Returns
   * <tt>true</tt> if and only if the specified object is also a list, both
   * lists have the same size, and all corresponding pairs of elements in the
   * two lists are <i>equal</i>. In other words, two lists are defined to be
   * equal if they contain the same elements in the same order. This
   * definition ensures that the equals method works properly across different
   * implementations of the <tt>student.SimpleArrayList</tt> interface.
   *
   * @param o
   * the object to be compared for equality with this list
   * @return <tt>true</tt> if the specified object is equal to this list
   */
   @Override
   boolean equals(Object o);

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. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks

//StudentArrayList.java

public class StudentArrayList<E> implements SimpleArrayList<E> {

      // attributes

      private Object[] array;

      private int count;

      // constructor initializing arrray with default capacity

      public StudentArrayList() {

            array = new Object[10];

            count = 0;

      }

      // private helper method to ensure given capacity when full

      private void ensureCapacity(int newSize) {

            // doing nothing if array has already enough capacity

            if (array.length >= newSize) {

                  return;

            }

            // creating a new array of twice size, copying elements from old array,

            // replacing with new one.

            Object[] tempArray = new Object[newSize];

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

                  tempArray[i] = array[i];

            array = tempArray;

      }

      @Override

      public int size() {

            return count;

      }

      @Override

      public boolean isEmpty() {

            return count == 0;

      }

      @Override

      public boolean contains(E o) {

            // looping and searching for o

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

                  if (array[i].equals(o)) {

                        // found

                        return true;

                  }

            }

            // not found

            return false;

      }

      @Override

      public E[] toArray() {

            // creating a new array

            E[] copy = (E[]) new Object[count];

            // copying elements

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

                  copy[i] = (E) array[i];

            }

            // returning the copy

            return copy;

      }

      @Override

      public void add(E e) {

            // if array is full, doubling capacity

            if (count == array.length) {

                  ensureCapacity(count * 2);

            }

            array[count++] = e;

      }

      @Override

      public void remove(E o) {

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

                  if (array[i].equals(o)) {

                        // found, shifting remaining elements to left

                        for (int j = i; j < count - 1; j++) {

                              array[j] = array[j + 1];

                        }

                        // updating count

                        count--;

                        return;

                  }

            }

      }

      @Override

      public boolean containsAll(SimpleArrayList<E> c) {

            // looping through all elements in c

            for (E element : c.toArray()) {

                  if (!contains(element)) {

                        // current element in c is not there in this list

                        return false;

                  }

            }

            return true;

      }

      @Override

      public boolean addAll(SimpleArrayList<E> c) {

            if (c.isEmpty()) {

                  return false; // no change

            }

            // adding all elements of c to this list

            for (E element : c.toArray()) {

                  add(element);

            }

            return true;

      }

      @Override

      public boolean addAll(int index, SimpleArrayList<E> c) {

            // if c is empty or if index is invalid, returning false

            if (c.isEmpty() || index < 0 || index > count) {

                  return false; // no change

            }

            // ensuring enough capacity

            ensureCapacity(count + c.size());

            // finding number of elements to be shifted

            int to_be_shifted = count - index;

            // if number of elements to be shifted is above 0,

            if (to_be_shifted > 0) {

                  // copying to_be_shifted elements FROM array starting from index

                  // position TO the same array at index=index + c.size()

                  System.arraycopy(array, index, array, index + c.size(),

                              to_be_shifted);

            }

            // now adding elements of c into this array starting from index position

            for (E element : c.toArray()) {

                  array[index++] = element;

            }

            //updating count and returning true

            count += c.size();

            return true;

      }

      @Override

      public boolean removeAll(SimpleArrayList<E> c) {

            // storing old size

            int oldSize = count;

            // looping and removing all elements from this list that is present on c

            for (E element : c.toArray()) {

                  remove(element);

            }

            // returning true if size changed (modified the list)

            return oldSize != count;

      }

      @Override

      public boolean retainAll(SimpleArrayList<E> c) {

            int oldSize = count;

            // looping and removing all elements from this list that is NOT present

            // on c

            for (E element : this.toArray()) {

                  if (!c.contains(element)) {

                        remove(element);

                  }

            }

            return oldSize != count;

      }

      @Override

      public void clear() {

            count = 0;

      }

      @Override

      public boolean equals(Object other) {

            if (other instanceof SimpleArrayList) {

                  // safe type casting

                  SimpleArrayList otherList = (SimpleArrayList) other;

                  // if size mismatch, returning false

                  if (size() != otherList.size()) {

                        return false;

                  }

                  // fetching other elements

                  E[] otherElements = (E[]) otherList.toArray();

                  // looping and checking if elements are same in same order

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

                        if (!array[i].equals(otherElements[i])) {

                              // not same

                              return false;

                        }

                  }

                  // all elements are equal, both lists are hence equal

                  return true;

            }

            // other is not a SimpleArrayList

            return false;

      }

}


Related Solutions

Create a Java class named ReadWriteCSV that reads the attached cis425_io.txt file that you will save...
Create a Java class named ReadWriteCSV that reads the attached cis425_io.txt file that you will save in your workspace as src/cis425_io.txt and displays the following table: -------------------------- | No | Month Name | Days | -------------------------- | 1 | January | 31 | | 2 | February | 28 | | 3 | March | 31 | | 4 | April | 30 | | 5 | May | 31 | | 6 | June | 30 |. | 7...
Create a custom Exception named IllegalTriangleSideException. Create a class named Triangle. The Triangle class should contain...
Create a custom Exception named IllegalTriangleSideException. Create a class named Triangle. The Triangle class should contain 3 double variables containing the length of each of the triangles three sides. Create a constructor with three parameters to initialize the three sides of the triangle. Add an additional method named checkSides with method header - *boolean checkSides() throws IllegalTriangleSideException *. Write code so that checkSides makes sure that the three sides of the triangle meet the proper criteria for a triangle. It...
Create a custom Exception named IllegalTriangleSideException. Create a class named Triangle. The Triangle class should contain...
Create a custom Exception named IllegalTriangleSideException. Create a class named Triangle. The Triangle class should contain 3 double variables containing the length of each of the triangles three sides. Create a constructor with three parameters to initialize the three sides of the triangle. Add an additional method named checkSides with method header - *boolean checkSides() throws IllegalTriangleSideException *. Write code so that checkSides makes sure that the three sides of the triangle meet the proper criteria for a triangle. It...
In java: -Create a class named Animal
In java: -Create a class named Animal
Create a Java class file for a Car class. In the File menu select New File......
Create a Java class file for a Car class. In the File menu select New File... Under Categories: make sure that Java is selected. Under File Types: make sure that Java Class is selected. Click Next. For Class Name: type Car. For Package: select csci2011.lab7. Click Finish. A text editor window should pop up with the following source code (except with your actual name): csci1011.lab7; /** * * @author Your Name */ public class Car { } Implement the Car...
Create a class named Employee and its child class named Salesperson. Save each class in its...
Create a class named Employee and its child class named Salesperson. Save each class in its own file. Name your class and source code file containing the main method homework.java. Make sure each class follows these specifications: 1. An employee has a name (String), employee id number (integer), hourly pay rate (double), a timesheet which holds the hours worked for the current week (double array) and email address (String). A salesperson also has a commission rate, which is a percentage...
In a package named "oop" create a Scala class named "Score" with the following: • A...
In a package named "oop" create a Scala class named "Score" with the following: • A constructor that takes an Int and stores it in a member variable named score • A method named scoreGoal that takes no parameters and has return type Unit that increments the score by 1 • A method named isWinner that takes a Score object as a parameter and returns a Boolean. The method returns true if this instances score is strictly greater than the...
JAVA PROGRAMMING. In this assignment, you are to create a class named Payroll. In the class,...
JAVA PROGRAMMING. In this assignment, you are to create a class named Payroll. In the class, you are to have the following data members: name: String (5 pts) id: String   (5 pts) hours: int   (5 pts) rate: double (5 pts) private members (5 pts) You are to create no-arg and parameterized constructors and the appropriate setters(accessors) and getters (mutators). (20 pts) The class definition should also handle the following exceptions: An employee name should not be empty, otherwise an exception...
Create a file named Good1 nano Good1 Type Welcome in the file and save it. What...
Create a file named Good1 nano Good1 Type Welcome in the file and save it. What command gives you a long listing of your filenames in the current directory, including permissions attached to each file. What command would you use to change a file’s permissions to include read, write and execute permission for the owner of the file only. Explain the following file permissions    a) 777          b) 765          c) 400          d) 666          e) 600         ...
Create a Java project called Lab3B and a class named Lab3B. Create a second new class...
Create a Java project called Lab3B and a class named Lab3B. Create a second new class named Book. In the Book class: Add the following private instance variables: title (String) author (String) rating (int) Add a constructor that receives 3 parameters (one for each instance variable) and sets each instance variable equal to the corresponding variable. Add a second constructor that receives only 2 String parameters, inTitle and inAuthor. This constructor should only assign input parameter values to title and...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT