Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

เกิดอะไรขึ้นเมื่อพยายามเพิ่มคีย์ซ้ำลงใน HashMap ใน Java

HashMap เป็นคลาสที่ implements interface Map ฐานบน Hash table อนุญาตให้มีค่า null และคีย์ null

คุณสามารถจัดเก็บคู่คีย์-ค่าในอ็อบเจกต์ HashMap ได้ หลังจากนั้นสามารถดึงค่าของคีย์แต่ละตัวได้ แต่ค่าที่ใช้เป็นคีย์ควรเป็นค่าเดียว (unique)

ค่าซ้ำ (Duplicate values)

คำสั่ง put ผูกค่ากับคีย์ที่ระบุ คือ หากเพิ่มคู่คีย์-ค่าที่คีย์มีอยู่แล้ว เมธอดนี้จะแทนที่ค่าที่มีอยู่ของคีย์นั้นด้วยค่าใหม่

ตัวอย่าง

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class DuplicatesInHashMap {
    public static void main(String args[]) {
        HashMap<String, Long> map = new HashMap<String, Long>();
        map.put("Krishna", 9000123456L);
        map.put("Rama", 9000234567L);
        map.put("Sita", 9000345678L);
        map.put("Bhima", 9000456789L);
        map.put("Yousuf ", 9000456789L);
        
        System.out.println("Values Stored . . . . . .");
        
        // ดึงค่าของ Hash map
        Iterator it1 = map.entrySet().iterator();
        System.out.println("Contents of the hashMap are: ");
        
        while(it1.hasNext()){
            Map.Entry<String, Long> ele = (Map.Entry) it1.next();
            System.out.print(ele.getKey() + " : ");
            System.out.print(ele.getValue());
            System.out.println();
        }
        
        map.put("Bhima", 0000000000L);
        map.put("Rama", 0000000000L);
        
        // ดึงค่าของ Hash map
        Iterator it2 = map.entrySet().iterator();
        System.out.println("Contents of the hashMap after inserting new key-value pair: ");
        
        while(it2.hasNext()){
            Map.Entry<String, Long> ele = (Map.Entry) it2.next();
            System.out.print(ele.getKey() + " : ");
            System.out.print(ele.getValue());
            System.out.println();
        }
    }
}

ผลลัพธ์

Values Stored . . . . . .
Contents of the hashMap are:
Yousuf : 9000456789
Krishna : 9000123456
Sita : 9000345678
Rama : 9000234567
Bhima : 9000456789

Contents of the hashMap after inserting new key-value pair:
Yousuf : 9000456789
Krishna : 9000123456
Sita : 9000345678
Rama : 0
Bhima : 0