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
MyLab Programming with Pearson eText -- Access Card -- for Introduction to Java Programming and Data Structures, Comprehensive Version
Additional Engineering Textbook Solutions
Introduction To Programming Using Visual Basic (11th Edition)
Mechanics of Materials (10th Edition)
Database Concepts (8th Edition)
Computer Science: An Overview (13th Edition) (What's New in Computer Science)
Thinking Like an Engineer: An Active Learning Approach (4th Edition)
Java How to Program, Early Objects (11th Edition) (Deitel: How to Program)
- 1. Complete the routing table for R2 as per the table shown below when implementing RIP routing Protocol? (14 marks) 195.2.4.0 130.10.0.0 195.2.4.1 m1 130.10.0.2 mo R2 R3 130.10.0.1 195.2.5.1 195.2.5.0 195.2.5.2 195.2.6.1 195.2.6.0 m2 130.11.0.0 130.11.0.2 205.5.5.0 205.5.5.1 R4 130.11.0.1 205.5.6.1 205.5.6.0arrow_forwardAnalyze the charts and introduce each charts by describing each. Identify the patterns in the given data. And determine how are the data points are related. Refer to the raw data (table):arrow_forward3A) Generate a hash table for the following values: 11, 9, 6, 28, 19, 46, 34, 14. Assume the table size is 9 and the primary hash function is h(k) = k % 9. i) Hash table using quadratic probing ii) Hash table with a secondary hash function of h2(k) = 7- (k%7) 3B) Demonstrate with a suitable example, any three possible ways to remove the keys and yet maintaining the properties of a B-Tree. 3C) Differentiate between Greedy and Dynamic Programming.arrow_forward
- What are the charts (with their title name) that could be use to illustrate the data? Please give picture examples.arrow_forwardA design for a synchronous divide-by-six Gray counter isrequired which meets the following specification.The system has 2 inputs, PAUSE and SKIP:• While PAUSE and SKIP are not asserted (logic 0), thecounter continually loops through the Gray coded binarysequence {0002, 0012, 0112, 0102, 1102, 1112}.• If PAUSE is asserted (logic 1) when the counter is onnumber 0102, it stays here until it becomes unasserted (atwhich point it continues counting as before).• While SKIP is asserted (logic 1), the counter misses outodd numbers, i.e. it loops through the sequence {0002,0112, 1102}.The system has 4 outputs, BIT3, BIT2, BIT1, and WAITING:• BIT3, BIT2, and BIT1 are unconditional outputsrepresenting the current number, where BIT3 is the mostsignificant-bit and BIT1 is the least-significant-bit.• An active-high conditional output WAITING should beasserted (logic 1) whenever the counter is paused at 0102.(a) Draw an ASM chart for a synchronous system to providethe functionality described above.(b)…arrow_forwardS A B D FL I C J E G H T K L Figure 1: Search tree 1. Uninformed search algorithms (6 points) Based on the search tree in Figure 1, provide the trace to find a path from the start node S to a goal node T for the following three uninformed search algorithms. When a node has multiple successors, use the left-to-right convention. a. Depth first search (2 points) b. Breadth first search (2 points) c. Iterative deepening search (2 points)arrow_forward
- We want to get an idea of how many tickets we have and what our issues are. Print the ticket ID number, ticket description, ticket priority, ticket status, and, if the information is available, employee first name assigned to it for our records. Include all tickets regardless of whether they have been assigned to an employee or not. Sort it alphabetically by ticket status, and then numerically by ticket ID, with the lower ticket IDs on top.arrow_forwardFigure 1 shows an ASM chart representing the operation of a controller. Stateassignments for each state are indicated in square brackets for [Q1, Q0].Using the ASM design technique:(a) Produce a State Transition Table from the ASM Chart in Figure 1.(b) Extract minimised Boolean expressions from your state transition tablefor Q1, Q0, DISPATCH and REJECT. Show all your working.(c) Implement your design using AND/OR/NOT logic gates and risingedgetriggered D-type Flip Flops. Your answer should include a circuitschematic.arrow_forwardA controller is required for a home security alarm, providing the followingfunctionality. The alarm does nothing while it is disarmed (‘switched off’). It canbe armed (‘switched on’) by entering a PIN on the keypad. Whenever thealarm is armed, it can be disarmed by entering the PIN on the keypad.If motion is detected while the alarm is armed, the siren should sound AND asingle SMS message sent to the police to notify them. Further motion shouldnot result in more messages being sent. If the siren is sounding, it can only bedisarmed by entering the PIN on the keypad. Once the alarm is disarmed, asingle SMS should be sent to the police to notify them.Two (active-high) input signals are provided to the controller:MOTION: Asserted while motion is detected inside the home.PIN: Asserted for a single clock cycle whenever the PIN has beencorrectly entered on the keypad.The controller must provide two (active-high) outputs:SIREN: The siren sounds while this output is asserted.POLICE: One SMS…arrow_forward
- 4G+ Vo) % 1.1. LTE1 : Q B NIS شوز طبي ۱:۱۷ کا A X حاز هذا على إعجاب Mohamed Bashar. MEDICAL SHOE شوز طبي ممول . اقوى عرض بالعراق بلاش سعر القطعة ١٥ الف سعر القطعتين ٢٥ الف سعر 3 قطع ٣٥ الف القياسات : 40-41-42-43-44- افحص وكدر ثم ادفع خدمة التوصيل 5 الف لكافة محافظات العراق ופרסם BNI SH ופרסם DON JU WORLD DON JU MORISO DON JU إرسال رسالة III Messenger التواصل مع شوز طبي تعليق باسم اواب حمیدarrow_forwardA manipulator is identified by the following table of parameters and variables:a. Obtain the transformation matrices between adjacent coordinate frames and calculate the global transformation matrix.arrow_forwardWhich tool takes the 2 provided input datasets and produces the following output dataset? Input 1: Record First Last Output: 1 Enzo Cordova Record 2 Maggie Freelund Input 2: Record Frist Last MI ? First 1 Enzo Last MI Cordova [Null] 2 Maggie Freelund [Null] 3 Jason Wayans T. 4 Ruby Landry [Null] 1 Jason Wayans T. 5 Devonn Unger [Null] 2 Ruby Landry [Null] 6 Bradley Freelund [Null] 3 Devonn Unger [Null] 4 Bradley Freelund [Null] OA. Append Fields O B. Union OC. Join OD. Find Replace Clear selectionarrow_forward
- EBK JAVA PROGRAMMINGComputer ScienceISBN:9781337671385Author:FARRELLPublisher:CENGAGE LEARNING - CONSIGNMENTC++ Programming: From Problem Analysis to Program...Computer ScienceISBN:9781337102087Author:D. S. MalikPublisher:Cengage LearningNp Ms Office 365/Excel 2016 I NtermedComputer ScienceISBN:9781337508841Author:CareyPublisher:Cengage
- Programming Logic & Design ComprehensiveComputer ScienceISBN:9781337669405Author:FARRELLPublisher:CengageNew Perspectives on HTML5, CSS3, and JavaScriptComputer ScienceISBN:9781305503922Author:Patrick M. CareyPublisher:Cengage LearningSystems ArchitectureComputer ScienceISBN:9781305080195Author:Stephen D. BurdPublisher:Cengage Learning