If you are talking about an instance of java.util.LinkedList :
while (!linkedlist.isEmpty()) { linkedlist.removeFirst(); }
If you are talking about an instance of any java.util.List :
while (!list.isEmpty()) { list.remove(0); }
bearing in mind that remove is an optional operation. However, depending on the implementation of the list, this can be terribly effective. For ArrayList this will be better:
while (!list.isEmpty()) { list.remove(list.size() - 1); }
Another alternative would be to iterate over the list and call Iterator.remove() for each element ... also an optional operation. (But then again, this can be terribly inefficient for some list implementations.)
If you are talking about a custom class of linked lists, then the answer depends on how you declared the structure of the internal structures of the list.
I suspect that if interviewers mentioned the clear() method, they expected a response in the context of a standard Java collection environment ... not for a class of related classes.
source share