Question

In: Computer Science

The implementations of the methods addAll, removeAll, retainAll are omitted in the MyList interface. Implement these...

The implementations of the methods addAll, removeAll, retainAll are omitted in the MyList interface. Implement these methods.


/** Adds the elements in otherList to this list.
* Returns true if this list changed as a result of the call */
public default boolean addAll(Collection<? extends E> c)


/** Removes all the elements in otherList from this list
* Returns true if this list changed as a result of the call */
public default boolean removeAll(Collection<?> c)


/** Retains the elements in this list that are also in otherList
* Returns true if this list changed as a result of the call */
public default boolean retainAll(Collection<?> c)


Write a test program that creates two MyArrayLists, list1 and list2, with the initial values {"Tom", "George", "Peter", "Jean", "Jane"} and {"Tom", "George", "Michael", "Michelle", "Daniel"}, then perform the following operations:
■ Invokes list1.addAll(list2), and displays list1 and list2.
■ Recreates list1 and list2 with the same initial values, invokes list1.removeAll(list2), and displays list1 and list2.
■ Recreates list1 and list2 with the same initial values, invokes list1.retainAll(list2), and displays list1 and list2.

Solutions

Expert Solution

package Feb23;

//TestMyArrayList.java
import java.util.*;

class MyArrayList<E> implements MyList<E> {
        public static final int INITIAL_CAPACITY = 16;
        private E[] data = (E[]) new Object[INITIAL_CAPACITY];
        private int size = 0; // Number of elements in the list

        /** Create an empty list */
        public MyArrayList() {
        }

        /** Create a list from an array of objects */
        public MyArrayList(E[] objects) {
                for (int i = 0; i < objects.length; i++)
                        add(objects[i]); // Warning: don’t use super(objects)!
        }

        @Override /** Add a new element at the specified index */
        public void add(int index, E e) {
                // Ensure the index is in the right range
                if (index < 0 || index > size)
                        throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);

                ensureCapacity();

                // Move the elements to the right after the specified index
                for (int i = size - 1; i >= index; i--)
                        data[i + 1] = data[i];

                // Insert new element to data[index]
                data[index] = e;

                // Increase size by 1
                size++;
        }

        /** Create a new larger array, double the current size + 1 */
        private void ensureCapacity() {
                if (size >= data.length) {
                        E[] newData = (E[]) (new Object[size * 2 + 1]);
                        System.arraycopy(data, 0, newData, 0, size);
                        data = newData;
                }
        }

        @Override /** Clear the list */
        public void clear() {
                data = (E[]) new Object[INITIAL_CAPACITY];
                size = 0;
        }

        @Override /** Return the element at the specified index */
        public E get(int index) {
                checkIndex(index);
                return data[index];
        }

        private void checkIndex(int index) {
                if (index < 0 || index >= size)
                        throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
        }

        @Override /** Return true if this list contains the element */
        public boolean contains(Object e) {
                for (int i = 0; i < size; i++)
                        if (e.equals(data[i]))
                                return true;

                return false;
        }

        @Override /**
                                 * Return the index of the first matching element in this list. Return -1 if no
                                 * match.
                                 */
        public int indexOf(Object e) {
                for (int i = 0; i < size; i++)
                        if (e.equals(data[i]))
                                return i;

                return -1;
        }

        @Override /**
                                 * Return the index of the last matching element in this list. Return -1 if no
                                 * match.
                                 */
        public int lastIndexOf(E e) {
                for (int i = size - 1; i >= 0; i--)
                        if (e.equals(data[i]))
                                return i;

                return -1;
        }

        @Override /**
                                 * Remove the element at the specified position in this list. Shift any
                                 * subsequent elements to the left. Return the element that was removed from the
                                 * list.
                                 */
        public E remove(int index) {
                checkIndex(index);

                E e = data[index];

                // Shift data to the left
                for (int j = index; j < size - 1; j++)
                        data[j] = data[j + 1];

                data[size - 1] = null; // This element is now null

                // Decrement size
                size--;

                return e;
        }

        @Override /**
                                 * Replace the element at the specified position in this list with the specified
                                 * element.
                                 */
        public E set(int index, E e) {
                checkIndex(index);
                E old = data[index];
                data[index] = e;
                return old;
        }

        @Override
        public String toString() {
                StringBuilder result = new StringBuilder("[");

                for (int i = 0; i < size; i++) {
                        result.append(data[i]);
                        if (i < size - 1)
                                result.append(", ");
                }

                return result.toString() + "]";
        }

        /** Trims the capacity to current size */
        public void trimToSize() {
                if (size != data.length) {
                        E[] newData = (E[]) (new Object[size]);
                        System.arraycopy(data, 0, newData, 0, size);
                        data = newData;
                } // If size == capacity, no need to trim
        }

        @Override /** Override iterator() defined in Iterable */
        public java.util.Iterator<E> iterator() {
                return new ArrayListIterator();
        }

        private class ArrayListIterator implements java.util.Iterator<E> {
                private int current = 0; // Current index

                @Override
                public boolean hasNext() {
                        return current < size;
                }

                @Override
                public E next() {
                        return data[current++];
                }

                @Override // Remove the element returned by the last next()
                public void remove() {
                        if (current == 0) // next() has not been called yet
                                throw new IllegalStateException();
                        MyArrayList.this.remove(--current);
                }
        }

        @Override /** Return the number of elements in this list */
        public int size() {
                return size;
        }
}

interface MyList<E> extends Collection<E> {
        /** Add a new element at the specified index in this list */
        public void add(int index, E e);

        /** Return the element from this list at the specified index */
        public E get(int index);

        /**
         * Return the index of the first matching element in this list. Return -1 if no
         * match.
         */
        public int indexOf(Object e);

        /**
         * Return the index of the last matching element in this list Return -1 if no
         * match.
         */
        public int lastIndexOf(E e);

        /**
         * Remove the element at the specified position in this list Shift any
         * subsequent elements to the left. Return the element that was removed from the
         * list.
         */
        public E remove(int index);

        /**
         * Replace the element at the specified position in this list with the specified
         * element and returns the new set.
         */
        public E set(int index, E e);

        @Override
        /** Add a new element at the end of this list */
        public default boolean add(E e) {
                add(size(), e);
                return true;
        }

        @Override
        /** Return true if this list contains no elements */
        public default boolean isEmpty() {
                return size() == 0;
        }

        @Override
        /**
         * Remove the first occurrence of the element e from this list. Shift any
         * subsequent elements to the left. Return true if the element is removed.
         */
        public default boolean remove(Object e) {
                if (indexOf(e) >= 0) {
                        remove(indexOf(e));
                        return true;
                } else
                        return false;
        }

        @Override
        /**
         * Adds the elements in otherList to this list. Returns true if this list
         * changed as a result of the call
         */
        public default boolean addAll(Collection<? extends E> c) {
                boolean status = false;
                for(E o : c) {
                        status = add(o) || status;
                }
                return status;
        }

        @Override /** Return true if this list contains the element */
        public default boolean contains(Object o) {
                if (indexOf((E) o) == -1)
                        return false;
                return true;
        }

        @Override
        /**
         * Returns true if this collection contains all of the elements in the specified
         * collection.
         */
        public default boolean containsAll(Collection<?> c) {
                for(Object o : c) {
                        if(!contains(o)) {
                                return false;
                        }
                }
                return true;
        }

        @Override
        /**
         * Removes all the elements in otherList from this list Returns true if this
         * list changed as a result of the call
         */
        public default boolean removeAll(Collection<?> c) {
                boolean status = false;
                for(Object o : c.toArray()) {
                        status = remove(o) || status;
                }
                return status;
        }

        @Override
        /**
         * Retains the elements in this list that are also in otherList Returns true if
         * this list changed as a result of the call
         */
        public default boolean retainAll(Collection<?> c) {
                // Left as an exercise
                boolean status = false;
                for(Object o: this.toArray()) {
                        if(!c.contains(o)) {
                                status = remove(o) || status;
                        }
                }
                
                return status;
        }

        @Override
        /** Returns an array containing all of the elements in this collection. */
        public default Object[] toArray() {
                Object[] temp = new Object[this.size()];
                for (int i = 0; i < this.size(); i++)
                        temp[i] = (Object) (this.get(i));
                if (size() > 0)
                        return (E[]) temp;
                else
                        return null;
        }

        @Override
  /** Returns an array containing all of the elements in this collection; 
   * the runtime type of the returned array is that of the specified array.
   */
  public default <T> T[] toArray(T[] array) {             
                int i = 0;
                for(E x: this) {
                        array[i++] = (T) x;
                }
                
                return array;
  }
}

public class TestMyArrayList {

        public static void main(String[] args) {
                new TestMyArrayList();
        }

        public TestMyArrayList() {
                String[] name1 = { "Tom", "George", "Peter", "Jean", "Jane" };
                String[] name2 = { "George", "Michael", "Michelle", "Daniel" };
                String[] name3 = { "Tom", "Peter" };

                MyList<String> list1 = new MyArrayList<String>(name1);
                MyList<String> list2 = new MyArrayList<String>(name2);
                MyList<String> list3 = new MyArrayList<String>(name3);
                System.out.println("list1:" + list1);
                System.out.println("list2:" + list2);
                System.out.println("list3:" + list3);
                System.out.println("\n\nlist1 contains all of list3? " + list1.containsAll(list3));
                System.out.println("\n\nlist2 contains all of list3? " + list2.containsAll(list3));
                System.out.println("\n\nlist1 removed all of list3? " + list1.removeAll(list3));
                System.out.println("list1:" + list1);
                System.out.println("\n\nlist2 removed all of list3? " + list2.removeAll(list3));
                System.out.println("list2:" + list2);
                list1 = new MyArrayList<String>(name1);
                list2 = new MyArrayList<String>(name2);
                list3 = new MyArrayList<String>(name3);
                System.out.println("\n\nlist1 retains all of list3? " + list1.retainAll(list3));
                System.out.println("list1 After retainAll:" + list1 + "\n");
                list1 = new MyArrayList<String>(name1);
                list1.add("Bahram");
                System.out.println("list1:" + list1);
                System.out.println("list2:" + list2);
                list1.addAll(list2);
                System.out.println("After addAll:" + list1 + "\n");
                Object[] nameArray1 = list1.toArray();

                System.out.println(new ArrayList(Arrays.asList(nameArray1)));

                String[] nameArray2 = new String[list1.size()];
                nameArray2 = list1.toArray(nameArray2);

                System.out.println(new ArrayList<String>(Arrays.asList(nameArray2)) + "\n");

        }

}
**************************************************

Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.

Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.


Related Solutions

For this problem you must define a simple generic interface PairInterface, and two implementations of the...
For this problem you must define a simple generic interface PairInterface, and two implementations of the interface, BasicPair and ArrayPair. a. Define a Java interface named PairInterface. A class that implements this interface allows creation of an object that holds a “pair” of objects of a specified type—these are referred to as the “first” object and the “second” object of the pair. We assume that classes implementing PairInterface provide constructors that accept as arguments the values of the pair of...
3. Which statement about methods in an interface is true? A.)All methods in an interface must...
3. Which statement about methods in an interface is true? A.)All methods in an interface must be explicitly declared as private or public. B.)All methods in an interface are automatically public. C.)All methods in an interface are automatically private. D.)All methods in an interface are automatically static.
(Implement MyLinkedList) The implementations of the methods contains(E e), get(int index), indexOf(E e), lastIndexOf(E e), and...
(Implement MyLinkedList) The implementations of the methods contains(E e), get(int index), indexOf(E e), lastIndexOf(E e), and set(int index, E e) are omitted in the MyLinkedList class. Implement these methods.
(Implementing Interfaces) Implement the following interface and classes: a. Interface IsCompetition, which has no constants and...
(Implementing Interfaces) Implement the following interface and classes: a. Interface IsCompetition, which has no constants and two methods (see the classes below for details about what these methods should do): i. getSummary(), ii. getCompetitors() b. Class Game: A game object is associated with a home team, away team, home score, away score, and a date of competition. It should only be created using the following constructor: Game(String HTeam, String ATeam, int HScore, int AScore, LocalDate date). A game is also...
data structure class: a. syntax for generics b. comparable interface c.how do you implement interface answer...
data structure class: a. syntax for generics b. comparable interface c.how do you implement interface answer for all of them please. answer for all of them please
JAVA Add static methods largest and smallest to the Measurable interface. The methods should return the...
JAVA Add static methods largest and smallest to the Measurable interface. The methods should return the object with the largest or smallest measure from an array of Measurable objects.
IN JAVA Step 1 Develop the following interface: Interface Name: ImprovedStackInterface Access Modifier: public Methods Name:...
IN JAVA Step 1 Develop the following interface: Interface Name: ImprovedStackInterface Access Modifier: public Methods Name: push Access modifier: public Parameters: item (data type T, parameterized type) Return type: void Throws: StackFullException Name: push Access modifier: public Parameters: item1 (data type T, parameterized type), item2 (data type T, parameterized type) Return type: void Throws: StackFullException Name: pop Access modifier: public Parameters: none Return type: void Throws: StackEmptyException Name: doublePop Access modifier: public Parameters: none Return type: void Throws: StackEmptyException Name:...
This is for a java program. Payroll System Using Inheritance and Polymorphism 1. Implement an interface...
This is for a java program. Payroll System Using Inheritance and Polymorphism 1. Implement an interface called EmployeeInfo with the following constant variables: FACULTY_MONTHLY_SALARY = 6000.00 STAFF_MONTHLY_HOURS_WORKED = 160 2. Implement an abstract class Employee with the following requirements: Attributes last name (String) first name (String) ID number (String) Sex - M or F Birth date - Use the Calendar Java class to create a date object Default argument constructor and argument constructors. Public methods toString - returning a string...
1. You are given Stack.java, an interface class for Stacks. /* Use an array to implement...
1. You are given Stack.java, an interface class for Stacks. /* Use an array to implement the Stack.java in a class called ArrayStack.java that uses Generics. Write a main function that creates two stacks, one containing 10 Integers and a different one containing 10 Strings, and reverses there contents using a method called reverse that takes as a paramater a Generic array. You will need to implement all the methods of Stack.java as well as create a toString method in...
write code in java and comment. thanks. the program is about interface . Implement the basics...
write code in java and comment. thanks. the program is about interface . Implement the basics of Fitness and types of Fitness: Aerobic. Implement specific Fitness types such as Swimming, Cycling, Fitness Task: public interface Fitness (10pts) This will be used as a starting point for deriving any specific Fitness type. Every fitness exercise type has one or more muscle group it affects. Therefor a Fitness has the following abstarct method (Note that all methods in an interface are abstract...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT