File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Anuradha Prasanna
Ranch Hand
Posts: 115
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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)
 
Ankit Garg
Sheriff
Posts: 9495
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Venu Chakravorty
Ranch Hand
Posts: 46
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 504
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ankit Garg
Sheriff
Posts: 9495
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How can I miss that
 
Mike Simmons
Ranch Hand
Posts: 3028
10
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic