Java TreeMap: Understanding Key Duplicates and Output
Jerry wrote the following code. What's the correct output?
Map<String, String> dataMap = new TreeMap<String, String>();
dataMap.put('tom', 'from batch 01');
dataMap.put('jerry', 'from batch 01');
dataMap.put('linda', 'from batch 01');
dataMap.put('tom', 'from batch 02');
System.out.println(dataMap.get('tom'));
A. 'from batch01' B. 'from batch02' C. 'tom' D. runtime error
Answer: B. 'from batch02'
Explanation:
TreeMap maintains a sorted order based on keys. When duplicate keys are encountered, the later insertion overrides the previous value associated with that key. In this case, the second insertion of 'tom' with the value 'from batch 02' overrides the first insertion. Therefore, dataMap.get('tom') returns the value associated with the last insertion, which is 'from batch 02'.
原文地址: https://www.cveoy.top/t/topic/oz0a 著作权归作者所有。请勿转载和采集!