Forums Register Login

collection doubt again

+Pie Number of slices to send: Send
You need to store elements in a collection that guarantees that no duplicates are stored. Which two interfaces provide that capability? (Choose Two)
A. java.util.Map
B. java.util.Set
C. java.util.List
D. java.util.StoredSet
E. java.util.StoredMap
F. java.util.Collection
Ans: B,D�.

Doubt A,E also guarantee unique values

pls help
regards,
gitesh
+Pie Number of slices to send: Send
Hi

For Map,wheather two objects are equal or not ,depends on equals method.If you won't override equals method ,no two objects are never equal,even if they are equal.

Thanks

Anil Kumar
+Pie Number of slices to send: Send
Yes Anil, but the same holds for Set and SortedSet - if the equals() method of the objects you put in always returns false, even if the objects are really equal, then you can store duplicates in a Set. It would be an ugly hack, and really a bug in your equals() method if you do this.

A Map stores key-value pairs. The keys have to be unique, but the values do not have to be unique. So a Map doesn't protect against duplicate values. However, the question is a little bit ambiguous. Indeed, you cannot have duplicate key-value pairs in a map.

(Note: Please quote your sources).
+Pie Number of slices to send: Send
Hi Jesper,

i am also confused with the question. The source is JavaChina.

What you told I came to understand that Map assures unique Key's and not values, so the answer here is not Map, but Set.

Gitesh
+Pie Number of slices to send: Send
Page 539, Chapter 7 of K&B states:

Collections come in four basic flavors:
- Lists Lists of things (classes that implement List).
- Sets Unique things (classes that implement Set).
- Maps Things with a unique ID (classes that implement Map).
- Queues Things arranged by the order in which they are to be processed.

That points to Set and Sorted set as the answer.

Maps store unique IDs, but IDs are not the elements you store, they are only identifiers you use to find your elements. Maps will store duplicate elements and Sets will not.
+Pie Number of slices to send: Send
Gitesh

Set and its implementations like SortedSet always ensure that only unique elements are there in the collection.

Try this handson example :



This will add to uniques Set only if the element is new and if its repeated it will figure in duplicate Set
+Pie Number of slices to send: Send
thanks Ranchers!!. Doubt cleared.
Look! I laid an egg! Why does it smell like that? Tiny ad, does this smell weird to you?
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 914 times.
Similar Threads
doubt in || and &&
Doubt with ==
GC doubt
Doubt in a Question
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 06:47:32.