aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes All the Collections classes implementing List are ordered? - question from examlab Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "All the Collections classes implementing List are ordered? - question from examlab" Watch "All the Collections classes implementing List are ordered? - question from examlab" New topic
Author

All the Collections classes implementing List are ordered? - question from examlab

Anuradha Prasanna
Ranch Hand

Joined: Mar 09, 2006
Posts: 115

What is the result of calling search with a valid List implementation?
Answers are: A)0 B)1 C)2 D)The result is undefined

D) is the correct answer.
But as all Lists(ArrayList, Vector, LinkedList) - all these are ordered Collections, the answer should be 1. why D)


SCJP 6.0 90%
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9305
    
  17

Is there any explanation given to why D is correct?? The only reason that I can think of is that clear method is optional for List implementations. So there's no guarantee that the actual implementation of the list will support the clear method and might throw an UnsupportedOperationException...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Venu Chakravorty
Ranch Hand

Joined: Aug 19, 2009
Posts: 46
A collection must be sorted before it can be searched.
Like this:
Collections.sort(list);
System.out.println(Collections.binarySearch(list, "a"));

Correct me if I am wrong.
Neha Daga
Ranch Hand

Joined: Oct 30, 2009
Posts: 504
Venu is right.
before seacrching a collection it should be sorted otherwise the result will be unpredictable.
read ch-7 K&B it explained there with an example.


SCJP 1.6 96%
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9305
    
  17

How can I miss that
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
There's another reason answer D is correct: a "valid list implementation" may still throw UnsupportedOperationException in response to some methods, such as add() or clear(). Try running this with
 
jQuery in Action, 2nd edition
 
subject: All the Collections classes implementing List are ordered? - question from examlab