Sample Final Q8

4 views
Skip to first unread message

lydial92

unread,
Apr 20, 2011, 3:07:44 AM4/20/11
to UBC CPSC 210
Hi, I'm working on the Sample Final 8a) and stuck about whether it's
appropriate to use a for loop for the containsAll method as it it
checks whether all of the elements of the collection is inside the
list. For example,

public boolean containsAll(Collection<E> c){
boolean eAllContain = false;
for (E element : c)
if (find(head.getSuccessor(), element) != null)
eAllContain = true;

return eAllContain;


}


Thanks~



Paul Carter

unread,
Apr 20, 2011, 12:51:53 PM4/20/11
to ubc-cp...@googlegroups.com
It is certainly appropriate to use a for-each loop to iterate over the collection c.

Note that an alternative to using the 'find' method is to use the 'contains' method to determine if the LinkedList contains a particular item. The reason we would favour the 'contains' method is that there's some chance that we might change the signature of the private helper method 'find' - if we implement it using iteration rather than recursion, for example, we could change the parameters - or we might even choose to eliminate this private helper method completely. If we were to make such modifications, your containsAll method will break. However, there is far less chance that we would modify the signature of the public 'contains' method, as doing so would break client code that makes use of this method (and there's potentially a huge amount of code that would do so).

I recommend that you add some tests to check whether or not your method below meets the given specification. Actually, let me state that more strongly: you absolutely must write some tests :-)

Paul

lydial92

unread,
Apr 20, 2011, 2:13:44 PM4/20/11
to UBC CPSC 210
Thanks! =)

cs 210

unread,
Apr 23, 2011, 3:07:17 AM4/23/11
to UBC CPSC 210
Question 8b.

I noticed that in the recursive version of the solution an accumulator
was used. I was just wondering if my solution would also be considered
recursive(I didn't use an accumulator).

/*
* Returns the index of the given element or -1 in the case when the
* element is not in the list.
*/
// recursive version
public int indexOf(E element) {
MyListNode<E> cursor = head.getSuccessor();
int index=0;

if(!this.contains(element)){
return -1;
}

if(!cursor.equals(element)){
index++;
return indexOf(cursor.getSuccessor().getElement());
}
else
return index;

}



Thanks.

cs 210

unread,
Apr 23, 2011, 3:10:37 AM4/23/11
to UBC CPSC 210
Sorry, actually that is not right. Never mind.
Reply all
Reply to author
Forward
0 new messages