Author Topic:   Util2
Umesh
ranch hand
posted March 04, 2000 02:38 PM             
What can contain objects that have a unique key field of
String type, if it is required to retrieve the objects using that
key field as an index?

A. Map ...ans
B. Set ...why not !!
C. List
D. Collection
E. Enumeration

Ramana Namuduri
greenhorn
posted March 04, 2000 03:06 PM             
Both Map and Set should contain only unique elements, but Map can be used for indexing purposes whereas indexing cannot be done for Set.

Tony Alicea
sheriff
posted March 04, 2000 03:59 PM             
Map (with the understanding that the key is an Object and not restricted to a String object).

maha anna
bartender
posted March 04, 2000 06:18 PM             
Ramana,
a small correction.Both element objects of Set and key elements of a Map are unique.
A Map can have duplicate elements with diff index keys
By the way, while testing this concept I found this. JDK doc, says entrySet() method in Map interface return type is Set. enterySet() returns the CollectionView of the elements in a Map. Further down JDK also says that, each element in the returned CollectionView is a key-value pair which is of class type Map.Entry Since the elements(not index keys) in a Map can have duplicates how come JDK says Set entrySet()? For keySet() it says the return type is Set which is convincing to me. Any clarifications..from any of you?
Thank you,
Wait a min, I think this means each key-value pair as such is considered to be unique. Then we can say it is Set
regds,
maha anna.
code:

import java.util.*;
class test{
public static void main(String[] args) {

HashSet hset = new HashSet();
hset.add("anna");
hset.add("anna");
hset.add("soorya");
System.out.println(hset.size()); //prints 2

TreeSet tset = new TreeSet();
tset.add("anna");
tset.add("anna");
tset.add("soorya");
System.out.println(tset.size()); //prints 2

HashMap hmap = new HashMap();
hmap.put("person1","anna");
hmap.put("person2","anna");
hmap.put("person3","soorya");
System.out.println(hmap.size()); //prints 3

Set st = hmap.entrySet();
System.out.println(st.size()); //prints 3 How
come a Set contains duplicate elements
here...?Does this mean each key-value pair as
such is considered to be unique?

TreeMap tmap = new TreeMap();
tmap.put("person1","anna");
tmap.put("person2","anna");
tmap.put("person3","soorya");
System.out.println(tmap.size()); //prints 3
}


}


[This message has been edited by maha anna (edited March 04, 2000).]

|