1A nitialize objects -) a HashMap object, stMap, that the key set is a set of St
ID: 3733031 • Letter: 1
Question
1A nitialize objects -) a HashMap object, stMap, that the key set is a set of String objects and the value set is a set of Student objects -) a TreeMap object, cardvalue, that the key set is a set of Card objects and the value set is a set of Integer objects. B. True or false? The key set of a IreeMap object is sorted. l The key set of a HashMap object is sorted. The value set of a HashMap object cannot have duplicated elements. C. What is the correct way to make a new List object that contains all elements of values of stap of #5, duplicates allowed (to reflect multiple mappings)?Explanation / Answer
1. Initialize Objects:
1. HashMap<Key, Value> map = new HasMap();
=> HashMap<String, Student> stmap = new HashMap();
can also be : Map<String, Student> stmap = new HashMap<String, Student>();
2. TreeMap<Key, Value> map = new TreeMap();
=> TreeMap<Card, Integer> cardValue = new TreeMap();
can also be : Map<Card, Integer> cardValue = new TreeMap<Card, Integer>();
2. i) The key set of TreeMap object is sorted: True.
Reason: The TreeMap store the key in form of a search tree (just like binary search tree) due to which keys remain sorted. This can be seen when we iterate over TreeMap using Iterator, sorted order is maintained.
ii) The key set of a HashMap object is sorted: False.
Reason: The HashMap store the keys in Hash Buckets due to which keys do not follows sorted order rather random order. This can be seen when we iterate over HashMap using Iterator, random order is always generated.
iii) The value set of a HashMap object cannot have duplicated elements: False.
Reason: Only Key set of HashMap object cannot have duplicated elements, but there is no such restriction on values set.
3. We can create a list of all values using function values() inherited from Map class, which return a list of values in TreeMap or Map.
=> List<Value> list = new ArrayList<Value>(map.values());
=> List<Student> list = new ArrayList<Student>(stmap.values());
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.