Question: In JAVA Language Add the following methods to the LinkedCollection class, and create a test driver for each to show that they work correctly. Code
In JAVA Language
Add the following methods to the LinkedCollection class, and create a test driver for each to show that they work correctly. Code each of these methods by accessing the internal variables of the LinkedCollection, not by calling the previously defined methods of the class.
String toString() creates and returns a string that correctly represents the current collection. Such a method could prove useful for testing and debugging the class and for testing and debugging applications that use the class. Assume each stored element already provides its own reasonable toString method.
int count(T target) returns a count of the number of elements e in the collection such that e.equals(target) is true.
void removeAll(T target) removes all elements e from the collection such that e.equals(target) is true.
LinkedCollection
package ch05.collections;
import support.LLNode;
public class LinkedCollection
{
protected LLNode
protected int numElements = 0; // number of elements in this collection
// set by find method
protected boolean found; // true if target found, else false
protected LLNode
protected LLNode
public LinkedCollection()
{
numElements = 0;
head = null;
}
23. public boolean add(T element)
24. // Adds element to this collection.
25. { 26. LLNodenewNode = new LLNode (element);
27. newNode.setLink(head);
28. head = newNode;
29. numElements++;
30. return true;
31. }
32. public boolean contains (T target) public T get(T target)
33. { { 34. find(target); find(target);
35. return found; if (found)
36. } return location.getInfo();
37. else
38. return null;
39. }
Array-Based
protected void find(T target)
{ location = 0;
found = false;
while (location < numElements)
{ if (elements[location].equals(target))
{ found = true;
return;
}
else
location++;
}
}
public boolean remove (T target)
// Removes an element e from this collection such that e.equals(target)
// and returns true; if no such element exists, returns false.
{ find(target);
if (found)
{ if (head == location)
head = head.getLink(); // remove first node
else
previous.setLink(location.getLink()); // remove node at location
numElements--;
}
return found;
}
Link-Based
protected void find(T target)
{
location = head;
found = false;
while (location != null)
{
if (location.getInfo().equals(target))
{
found = true;
return;
}
else
{
previous = location;
location = location.getLink();
}
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
