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

ความแตกต่างระหว่าง EnumMap และ HashMap ใน Java

EnumMap vs HashMap

EnumMap (JDK 5+)

  • Specialized Map สำหรับ enum keys
  • Keys ต้องเป็น enum type เดียวกัน
  • Internal: ใช้ Array -> compact และ efficient
  • ไม่ allow null key (NullPointerException)
  • Operations: constant time -> เร็วกว่า HashMap
  • เก็บ keys ตาม natural order ของ enum

HashMap

  • General-purpose Map implementation
  • Allow one null key และ multiple null values
  • Internal: ใช้ Hashtable (hash buckets)
  • Constant-time performance สำหรับ get/put (สมมติ hash function กระจายดี)
  • ไม่ ordered

ตารางเปรียบเทียบ

KeyEnumMapHashMap
BasicSpecialized for enum keysGeneral Map implementation
Null KeyNot allowedAllowed (one null key)
PerformanceFaster (array-based, constant time)Slower (hash-based)
InternalArrayHashtable/buckets
OrderingNatural order of enum keysNot ordered

ตัวอย่าง EnumMap

EnumMap<LaptopEnum, String> map = new EnumMap<>(LaptopEnum.class);
map.put(LaptopEnum.HCL, "100");
map.put(LaptopEnum.DELL, "200");
map.put(LaptopEnum.IBM, "300");

ตัวอย่าง HashMap

Map<String, String> map = new HashMap<>();
map.put("HCL", "100");
map.put("DELL", "200");
map.put("IBM", "300");

สรุป

ใช้ EnumMap เมื่อ key เป็น enum type (เร็วกว่า เล็กกว่า ordered) ใช้ HashMap สำหรับ general-purpose key-value storage