Assume the following methods are defined in Mylist /** Adds the elements in othe
ID: 675282 • Letter: A
Question
Assume the following methods are defined in Mylist
/** Adds the elements in otherList to this list.
* Returns true if this list changed as a result of the call */ public boolean addAll(MyList<E> otherList);
/** Removes all the elements in otherList from this list
* Returns true if this list changed as a result of the call */ public boolean removeAll(MyList<E> otherList);
/** Retains the elements in this list that are also in otherList * Returns true if this list changed as a result of the call */ public boolean retainAll(MyList<E> otherList);
Based on the implementation of addAll method given below, please implement removeAll and retainAll methods.
/** Adds the elements in otherList to this list.
* Returns true if this list changed as a result of the call */
public boolean addAll(MyList<E> otherList) {
for (int i = 0; i < otherList.size(); i++)
}
/** Removes all the elements in otherList from this list
* Returns true if this list changed as a result of the call */
public boolean removeAll(MyList<E> otherList) {
}
/** Retains the elements in this list that are also in otherList
* Returns true if this list changed as a result of the call */
public boolean retainAll(MyList<E> otherList) {
}
Explanation / Answer
Solution:
/** Adds the elements in otherList to this list.
* Returns true if this list changed as a result of the call */
public boolean addAll(MyList<E> otherList) {
for (int i = 0; i < otherList.size(); i++)
myList.add(otherList.get(i));
if (myList.size() > 0)
return true;
else
return false;
}
//===================================================
/** Removes all the elements in otherList from this list
* Returns true if this list changed as a result of the call */
public boolean removeAll(MyList<E> otherList) {
int n=myList.size();
for (int i = 0; i < otherList.size(); i++)
myList.remove(otherList.get(i));
if (myList.size()!=n)
return true;
else
return false;
}
//=============================================================
/** Retains the elements in this list that are also in otherList
* Returns true if this list changed as a result of the call */
public boolean retainAll(MyList<E> otherList) {
int n=myList.size();
for (int i = 0; i < otherList.size(); i++)
myList.retainAll(otherList);
if (myList.size()!=n)
return true;
else
return false;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.