Question: Directed Lab Work Problem I: Common objects in two lists Suppose that aList and bList are instances of java.util.ArrayList. Use two iterators to find and
Directed Lab Work
Problem I: Common objects in two lists
Suppose that aList and bList are instances of java.util.ArrayList. Use two iterators to find and display all the items that are common in both lists.
One way to do this is to scan the items in the first list aList and for each item currentItem, scan the entire bList, checking its elements consecutively for equality to currentItem. The basic idea is to use an iterator for scanning the items in each list, e.g. aIterator and bIterator.
Follow the steps below.
Step 1. Create a new Eclipse project Lab20, a class CommonItems and a method findCommon in it:
findCommon(ArrayList
Step 2. In the findCommon method create an iterator ial for aList.
Step 3. Use the iterator in a while loop to consecutively access each element of the aList.
Step 4. Within the loop, create an iterator ibl for bList.
Step 5. Create a Boolean variable found to indicate whether the current item from the first list is equal to the currently considered item from the second list. Initialize it to false.
Step 6. Write a nested while loop using the iterator ibl to access each item from the second list in turn. At each step of the loop, check whether the current element from the first list is equal to the current element from the second list, and if so, assign true to the variable found.
Step 7. Upon exiting the nested loop, if the current item from aList is equal to at least one item from bList, print it.
Step 8. Create a main method in the CommonItems class for testing the findCommon method.
Step 9. Declare two arrays of strings, a and b and initialize them with some values.
Step 10. Declare two lists of type ArrayList - alist and blist, and add the values from the arrays a and b to them correspondingly (in a loop).
Step 11. Call the findCommon() method to find the common items in the lists and print the result.
Checkpoint: Test your program by executing the CommonItems class.
ListInterface.java
/** An interface for the ADT list. Entries in the list have positions that begin with 1.
@author Frank M. Carrano @version 3.0 */ public interface ListInterface
ListWithIteratorInterface.java
import java.util.Iterator; /** An interface for the ADT list that has an iterator. @author Frank M. Carrano @author Timothy M. Henry @version 4.0 */ public interface ListWithIteratorInterface
LinkedListWithIterator.java
import java.util.Iterator; import java.util.NoSuchElementException; /** A class that implements the ADT list by using a chain of nodes. The list has an iterator. The class is similar to LList. @author Frank M. Carrano @author Timothy M. Henry @version 4.0 */ public class LinkedListWithIterator
public LinkedListWithIterator() { initializeDataFields(); } // end default constructor
public void clear() { initializeDataFields(); } // end clear public void add(T newEntry) // OutOfMemoryError possible { Node newNode = new Node(newEntry);
if (isEmpty()) firstNode = newNode; else // Add to end of non-empty list { Node lastNode = getNodeAt(numberOfEntries); lastNode.setNextNode(newNode); // Make last node reference new node } // end if numberOfEntries++; } // end add
public void add(int newPosition, T newEntry) // OutOfMemoryError possible { if ((newPosition >= 1) && (newPosition <= numberOfEntries + 1)) { Node newNode = new Node(newEntry); if (newPosition == 1) // Case 1 { newNode.setNextNode(firstNode); firstNode = newNode; } else // Case 2: list is not empty { // and newPosition > 1 Node nodeBefore = getNodeAt(newPosition - 1); Node nodeAfter = nodeBefore.getNextNode(); newNode.setNextNode(nodeAfter); nodeBefore.setNextNode(newNode); } // end if numberOfEntries++; } else throw new IndexOutOfBoundsException("Illegal position given to add operation."); } // end add
public T remove(int givenPosition) { T result = null; // Return value if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) { assert !isEmpty(); if (givenPosition == 1) // Case 1: remove first entry { result = firstNode.getData(); // Save entry to be removed firstNode = firstNode.getNextNode(); } else // Case 2: not first entry { Node nodeBefore = getNodeAt(givenPosition - 1); Node nodeToRemove = nodeBefore.getNextNode(); Node nodeAfter = nodeToRemove.getNextNode(); nodeBefore.setNextNode(nodeAfter); result = nodeToRemove.getData(); // Save entry to be removed } // end if numberOfEntries--; return result; // Return removed entry } else throw new IndexOutOfBoundsException("Illegal position given to remove operation."); } // end remove
public T replace(int givenPosition, T newEntry) { if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) { assert !isEmpty(); Node desiredNode = getNodeAt(givenPosition); T originalEntry = desiredNode.getData(); desiredNode.setData(newEntry); return originalEntry; } else throw new IndexOutOfBoundsException("Illegal position given to replace operation."); } // end replace public T getEntry(int givenPosition) { if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) { assert !isEmpty(); return getNodeAt(givenPosition).getData(); } else throw new IndexOutOfBoundsException("Illegal position given to getEntry operation."); } // end getEntry public T[] toArray() { // The cast is safe because the new array contains null entries @SuppressWarnings("unchecked") T[] result = (T[])new Object[numberOfEntries]; int index = 0; Node currentNode = firstNode; while ((index < numberOfEntries) && (currentNode != null)) { result[index] = currentNode.getData(); currentNode = currentNode.getNextNode(); index++; } // end while return result; } // end toArray
public boolean contains(T anEntry) { boolean found = false; Node currentNode = firstNode; while (!found && (currentNode != null)) { if (anEntry.equals(currentNode.getData())) found = true; else currentNode = currentNode.getNextNode(); } // end while return found; } // end contains
public int getLength() { return numberOfEntries; } // end getLength
public boolean isEmpty() { boolean result;
if (numberOfEntries == 0) // Or getLength() == 0 { assert firstNode == null; result = true; } else { assert firstNode != null; result = false; } // end if
return result; } // end isEmpty public Iterator
public Iterator
private class IteratorForLinkedList implements Iterator
private IteratorForLinkedList() { nextNode = firstNode; } // end default constructor public boolean hasNext() { return nextNode != null; } // end hasNext
public T next() { if (hasNext()) { Node returnNode = nextNode; // Get next node nextNode = nextNode.getNextNode(); // Advance iterator return returnNode.getData(); // Return next entry in iteration } else throw new NoSuchElementException("Illegal call to next(); " + "iterator is after end of list."); } // end next
public void remove() { throw new UnsupportedOperationException("remove() is not " + "supported by this iterator"); } // end remove } // end IteratorForLinkedList private class Node { private T data; // Entry in list private Node next; // Link to next node private Node(T dataPortion) { data = dataPortion; next = null; } // end constructor private Node(T dataPortion, Node nextNode) { data = dataPortion; next = nextNode; } // end constructor private T getData() { return data; } // end getData private void setData(T newData) { data = newData; } // end setData private Node getNextNode() { return next; } // end getNextNode private void setNextNode(Node nextNode) { next = nextNode; } // end setNextNode } // end Node } // end LinkedListWithIterator
Driver.java
import java.util.Iterator; /** A driver that demonstrates the class LinkedListWithIterator.
*/ public class Driver { public static void main(String[] args) { testIterator(); } // end main
public static void testIterator() { ListWithIteratorInterface
System.out.println(" Testing the displayList method "); displayListI(myList); } // end testIterator
public static void displayListI(ListWithIteratorInterface
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
