Concept explainers
(Implement set operations in MyList) The implementations of the methods addAll, removeAll, retainAll, toArray(), and toArray(T[]) are omitted in the MyList interface. Implement these methods. Test your new MyList class using the code at liveexample.pearsoncmg.com/test/ Exercise24_01Test.txt.
MyList
Program plan:
- Import required packages.
- Declare the main class named “Main”.
- Give the main method “public static void main ()”.
- Declare a default constructor and data members.
- Prompt the user to get the input.
- Print the value of list1 and list2.
- Print the result by calling the function “addAll()”.
- Print the value of list1 and list2.
- Print the result by calling the method “removeAll()”.
- Print the value of list1 and list2.
- Print the result by calling the method “retainAll()”.
- Print the value of list1 and list2.
- Print the result by calling the method “containsAll()”.
- Includes an interface “MyList”
- Define a method to add a new element at the specified index in the list.
- Define a method to return the element from this list at the specified index
- Define a method to return the index of the first matching element in this list.
- Define a method to return the index of the last matching element in this list
- Define a method to remove the element at the specified position in this list
- Define a method to replace the element at the specified position in this list
- Define a method to add a new element at the end of this list
- Define a method to return true if this list contains no elements
- Define a method to remove the first occurrence of the element e from this list
- Define a method to check whether the elements are present or not
- Define a method to add the elements in otherList to this list.
- Define a method to retains the elements in this list that are also in otherList
- Define a class “MyArrayList”.
- Declare a variable “sum” and assign 0 to it.
- Declare data members and default constructor.
- Create a list from an array of object.
- Define a method to add a new element at the specified index
- Define a method to create a larger array which is double the current size.
- Define a method to clear the list.
- Define a method to return true if the list contains the element.
- Define a method to return the element at the specified index.
- Define a method to trim the capacity to current size.
- Define a method to return the number of element in the list.
- Give the main method “public static void main ()”.
The below program includes the methods addAll(), removeAll(), retainAll(), toArray(), and toArray(T[]) which were omitted in the MyList interface.
Explanation of Solution
Program:
//import required packages
import java.util.*;
//class definition
public class Exercise24_01 {
//define main method
public static void main(String[] args) {
new Exercise24_01();
}
//default constructor
public Exercise24_01() {
Scanner input = new Scanner(System.in);
//data members
String[] name1 = new String[5];
String[] name2 = new String[5];
String[] name3 = new String[2];
//prompt user to get the input
System.out.print("Enter five strings for array name1 separated by space: ");
for (int i = 0; i < 5; i++) {
name1[i] = input.next();
}
//prompt the user to get the input
System.out.print("Enter five strings for array name2 separated by space: ");
for (int i = 0; i < 5; i++) {
name2[i] = input.next();
}
//prompt user to get the input
System.out.print("Enter two strings for array name3 separated by space: ");
for (int i = 0; i < 2; i++) {
name3[i] = input.next();
}
MyList<String> list1 = new MyArrayList<>(name1);
MyList<String> list2 = new MyArrayList<>(name2);
//print the value of list1
System.out.println("list1:" + list1);
//print the value of list2
System.out.println("list2:" + list2);
//calling addAll function
list1.addAll(list2);
//print the result
System.out.println("After addAll:" + list1 + "\n");
list1 = new MyArrayList<>(name1);
list2 = new MyArrayList<>(name2);
//print the value of list1
System.out.println("list1:" + list1);
//print the value of list2
System.out.println("list2:" + list2);
//calling removeAll function
list1.removeAll(list2);
//print the result
System.out.println("After removeAll:" + list1 + "\n");
list1 = new MyArrayList<>(name1);
list2 = new MyArrayList<>(name2);
//print the value of list1
System.out.println("list1:" + list1);
//print the value of list2
System.out.println("list2:" + list2);
//calling the retainAll function
list1.retainAll(list2);
//print the result
System.out.println("After retainAll:" + list1 + "\n");
list1 = new MyArrayList<>(name1);
list2 = new MyArrayList<>(name2);
//print the value of list1
System.out.println("list1:" + list1);
//print the value of list2
System.out.println("list2:" + list2);
//calling the retainAll function
list1.retainAll(list2);
//print the result
System.out.println("list1 contains all list2? " + list1.containsAll(list2) + "\n");
list1 = new MyArrayList<>(name1);
list2 = new MyArrayList<>(name3);
//print the value of list1
System.out.println("list1:" + list1);
//print the value of list2
System.out.println("list2:" + list2);
//print the result
System.out.println("list1 contains all list2? " + list1.containsAll(list2) + "\n");
Object[] name4 = list1.toArray();
//print the result
System.out.print("name4: ");
for (Object e: name4) {
System.out.print(e + " ");
}
String[] name5 = new String[list1.size()];
String[] name6 = list1.toArray(name5);
//print the result
System.out.print("\nname6: ");
for (Object e: name6) {
System.out.print(e + " ");
}
}
//includes the interface
public interface MyList<E> extends java.util.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
/*method to check whether the elements are present or not */
public default boolean containsAll(Collection<?> c) {
for (Object e: c)
if (!this.contains(e))
return false;
return true;
}
/* Adds the elements in otherList to this list.
Returns true if this list changed as a result of the call */
@Override
public default boolean addAll(Collection<? extends E> c) {
for (E e: c)
this.add(e);
return c.size() > 0;
}
/* Removes all the elements in otherList from this list Returns true if this list changed as a result of the call */
@Override
public default boolean removeAll(Collection<?> c) {
boolean changed = false;
for (Object e: c) {
if (remove(e))
changed = true;
}
return changed;
}
/* Retains the elements in this list that are also in otherList, Returns true if this list changed as a result of the call */
@Override
public default boolean retainAll(Collection<?> c) {
boolean changed = false;
for (int i = 0; i < this.size(); ) {
if (!c.contains(this.get(i))) {
this.remove(get(i));
changed = true;
}
else
i++;
}
return changed;
}
@Override
public default Object[] toArray() {
// Left as an exercise
Object[] result = new Object[size()];
for (int i = 0; i < size(); i++) {
result[i] = this.get(i);
}
//return statement
return result;
}
@Override
public default <T> T[] toArray(T[] a) {
// Left as an exercise
for (int i = 0; i < size(); i++) {
a[i] = (T)this.get(i);
}
//return statement
return a;
}
}
//class definition
public class MyArrayList<E> implements MyList<E> {
//data members
public static final int INITIAL_CAPACITY = 16;
private E[] data = (E[])new Object[INITIAL_CAPACITY];
private int size = 0;
// 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]);
}
@Override /* Add a new element at the specified index */
public void add(int index, E e) {
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 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 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 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;
// 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> {
// Current index
private int current = 0;
@Override
public boolean hasNext() {
return (current < size);
}
@Override
public E next() {
return data[current++];
}
@Override
public void remove() {
MyArrayList.this.remove(current);
}
}
@Override /* Return the number of elements in this list */
public int size() {
return size;
}
}
}
Enter five strings for array name1 separated by space: tom george peter jean jane
Enter five strings for array name2 separated by space: tom george michael michelle daniel
Enter two strings for array name3 separated by space: tom peter
list1:[tom, george, peter, jean, jane]
list2:[tom, george, michael, michelle, daniel]
After addAll:[tom, george, peter, jean, jane, tom, george, michael, michelle, daniel]
list1:[tom, george, peter, jean, jane]
list2:[tom, george, michael, michelle, daniel]
After removeAll:[peter, jean, jane]
list1:[tom, george, peter, jean, jane]
list2:[tom, george, michael, michelle, daniel]
After retainAll:[tom, george]
list1:[tom, george, peter, jean, jane]
list2:[tom, george, michael, michelle, daniel]
list1 contains all list2? false
list1:[tom, george, peter, jean, jane]
list2:[tom, peter]
list1 contains all list2? true
name4: tom george peter jean jane
name6: tom george peter jean jane
Want to see more full solutions like this?
Chapter 24 Solutions
Introduction to Java Programming and Data Structures, Comprehensive Version (11th Edition)
Additional Engineering Textbook Solutions
Starting Out with Java: Early Objects (6th Edition)
C++ How to Program (10th Edition)
Database Concepts (8th Edition)
Starting Out with Java: From Control Structures through Data Structures (3rd Edition)
Modern Database Management (12th Edition)
Starting Out with Programming Logic and Design (5th Edition) (What's New in Computer Science)
- 2. Revise the genericStack class we did in the class to implement it using an array instead of ArrayList. You need to check the array size before adding a new element. If it is full, create a new array that double the current size and copy the elements from the current to the new array and then add the new array. (2 points) 3. Use the genericStack class we did the class (not the one in question 2), implement the binary search public static <E extends Comparable<E>) int binarySearch (E[] list, E key) and a method that returns the maximum value element public static <E extends Comparable<E>) E max(E[] list (2 points)arrow_forwardJava Collection Framework. (https://docs.oracle.com/javase/8/docs/technotes/guides/collections/overview.html) A collectionis an object that represents a group of objects. There are several classes that implement the collection interface. Examples of them are ArrayList, HashMap and LinkedList. Please make a report for each of ArrayList, HashMap and LinkedList including the description of the class and its major methods. Please specify the 3 real world problems to apply each class (ArrayList, HashMap and LinkedList). Make 3 code snippets to solve the real-world problem. The code snippet can be written in pseudo code. In the code snippets, please create an instance of each of the class, and use its key methods. Make sure the # of key methods in use for each class should be over 6.arrow_forwardCompare and contrast the array and arrayList. Give at least one example that describe when to use arrayList compared to an array.arrow_forward
- Please use java. In this assignment, you will implement a class calledCustomIntegerArrayList. This class represents a fancy ArrayList that stores integers and supports additional operations not included in Java's built-in ArrayList methods. For example, the CustomIntegerArrayList class has a “splice” method which removes a specified number of elements from the CustomIntegerArrayList, starting at a given index. For a CustomIntegerArrayList that includes: 1, 2, 3, 4, and 5, calling splice(1, 2) will remove 2 items starting at index 1. This will remove 2 and 3 (the 2nd and 3rd items). The Cu stomIntegerArrayList class has 2 different (overloaded) constructors. (Remember, an overloaded constructor is a constructor that has the same name, but a different number, type, or sequence of parameters, as another constructor in the class.) Having 2 different constructors means you can create an instance of the CustomIntegerArrayList class in 2 different ways, depending on which constructor…arrow_forwardTrue or False? Our LBList class inherits from the ABList class. Please explain.arrow_forward(b) Write the method isBalanced, which returns true when the delimiters are balanced and returns false otherwise. The delimiters are balanced when both of the following conditions are satisfied; otherwise, they are not balanced. When traversing the ArrayList from the first element to the last element, there is no point at which there are more close delimiters than open delimiters at or before that point. The total number of open delimiters is equal to the total number of close delimiters. Consider a Delimiters object for which openDel is "<sup>" and closeDel is "</sup>".The examples below show different ArrayList objects that could be returned by calls togetDelimitersList and the value that would be returned by a call to isBalanced.Example 1The following example shows an ArrayList for which isBalanced returns true. As tokens areexamined from first to last, the number of open delimiters is always greater than or equal to the number of close delimiters. After examining all…arrow_forward
- The implementations of the methods addAll, removeAll, retainAll, retainAll, containsAll(), and toArray(T[]) are omitted in the MyList interface. Implement these methods. Use the template at https://liveexample.pearsoncmg.com/test/Exercise24_01_13e.txt to implement these methods this the code i have for the write your own code part import java.util.Iterator; interface MyList<E> extends java.util.Collection<E> { void add(int index, E e); boolean contains(Object e); E get(int index); int indexOf(Object e); int lastIndexOf(E e); E remove(int index); E set(int index, E e); void clear(); boolean isEmpty(); Iterator<E> iterator(); boolean containsAll(java.util.Collection<?> c); boolean addAll(java.util.Collection<? extends E> c); boolean removeAll(java.util.Collection<?> c); boolean retainAll(java.util.Collection<?> c); Object[] toArray(); <T> T[] toArray(T[] a); int size();} and its…arrow_forwardYou are required to complete the LinkedList class. This class is used as a linked list that has many methods to perform operations on the linked list. To create a linked list, create an object of this class and use the addFirst or addLast or add(must be completed) to add nodes to this linked list. Your job is to complete the empty methods. For every method you have to complete, you are provided with a header, Do not modify those headers(method name, return type or parameters). You have to complete the body of the method. package chapter02; public class LinkedList { protected LLNode list; public LinkedList() { list = null; } public void addFirst(T info) { LLNode node = new LLNode(info); node.setLink(list); list = node; } public void addLast(T info) { LLNode curr = list; LLNode newNode = new LLNode(info); if(curr == null) { list = newNode; } else { while(curr.getLink() !=…arrow_forwarddefine Remove method.arrow_forward
- What are the two ways to remove duplicates from ArrayList?arrow_forward4 O T O I D06 It is time for you to demonstrate your skills in a project of your own choice. You must DESIGN, ANALYSE AND CODE any method for the GENERIC MyLinkedList class that will manipulate the linked list. You can decide yourself what it should be following the specification below: 1. Purpose: The method must make logical sense - it should be of some purpose to somebody. You should describe in the text who will use the method for which purpose. 2. Clearly explain the problem. Then clearly explain how your method will solve it. 3. Test program: Test the method using a wranned class like Integer l Filters Add a caption. > Status (Contacts)arrow_forwardIn this assignment, you will compare the performance of ArrayList and LinkedList. More specifically, your program should measure the time to “get” and “insert” an element in an ArrayList and a LinkedList.You program should 1. Initializei. create an ArrayList of Integers and populate it with 100,000 random numbersii. create a LinkedList of Integers and populate it with 100,000 random numbers2. Measure and print the total time it takes to i. get 100,000 numbers at random positions from the ArrayList 3. Measure and print the total time it takes to i. get 100,000 numbers at random positions from the LinkedList 4. Measure and print the total time it takes to i. insert 100,000 numbers in the beginning of the ArrayList 5. Measure and print the total time it takes to i. insert 100,000 numbers in the beginning of the LinkedList 6. You must print the time in milliseconds (1 millisecond is 1/1000000 second).A sample run will be like this:Time for get in ArrayList(ms): 1Time for get in…arrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education