Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Design for the Mind this week in the Design 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
  • 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: 9518
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • 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
  • 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
  • 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: 9518
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How can I miss that
 
Mike Simmons
Ranch Hand
Posts: 3039
10
  • 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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic