Question: Define an equals(Object) method for Lists. Two lists are equal if and only if they store the same values (in the same order). An ArrayList
Define an equals(Object) method for Lists. Two lists are equal if and only if they store the same values (in the
same order). An ArrayList can be equal to a LinkedList. You can put the API in your List interface:
/** @return true only if the parameter obj is a List and contains the same
elements
* (in the same sequence) as this List.
*/ boolean equals (Object obj); You may use the instanceof operator to determine whether the parameter is a List. If so, cast it as a List, storing a reference to it in a local variable. Your solution should be efficient. Test your solution with DriverLabEquals. Hints:
First compare the sizes of the two lists. If they have different sizes, they could not be equal.
Use Iterators. ListIterator:
package list;
import java.util.ListIterator;
public interface List
/** * @return this List as a String */ public String toString(); /** * Remove the first occurrence of the given object from this List. * @return true iff it was removed */ boolean remove (Object obj); /** * @return an Iterator for this List */ Iterator
package list;
public class ArrayList
{
private int size = 0;
private E[] values;
public ArrayList()
{
this (10);
}
//parametrized constructor
public ArrayList(int cap)
{
values = (E[]) new Object[cap];
}
//implementing abstract functions from interface
public E get (int ndx)
{
return values[ndx];
}
public E set(int ndx, E value)
{
E result = values[ndx];
values[ndx] = value;
return result;
}
public void add(E value)
{
add(size,value);
}
public void add(int ndx, E value)
{
if (values.length == size)
alloc();
for(int i = size; i > ndx; i--)
values[i] = values[i-1];
values[ndx] = value;
size++;
}
private void alloc()
{
E[] tempArray = (E[]) new Object[2*values.length]; for(int i = 0; i < size; i++) tempArray[i] = values [i];
values = tempArray; }
public E remove(int ndx) { E result = values[ndx];
for(int i = ndx; i < size-1; i++) values[i] = values [i + 1];
size--; return result; }
public int size() { return size; }
public boolean isEmpty() { if(size==0) return true; return false; }
public void clear()
{
for(int i=0;i values[i]=(E)new Object(); size=0; } public boolean contains(Object obj) { if(indexOf(obj)==-1) return false; return true; } public int indexOf(Object obj) { for(int i=0;i public String toString() { String s="["; for(int i=0;i public boolean remove(Object obj) { int pos = indexOf(obj); if(pos != -1) { remove(pos); return true; } else { return false; } } @Override public E remove(String string) { // TODO Auto-generated method stub return null; } public Iterator package list; public class LinkedList
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
