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
ตารางเปรียบเทียบ
| Key | EnumMap | HashMap |
|---|---|---|
| Basic | Specialized for enum keys | General Map implementation |
| Null Key | Not allowed | Allowed (one null key) |
| Performance | Faster (array-based, constant time) | Slower (hash-based) |
| Internal | Array | Hashtable/buckets |
| Ordering | Natural order of enum keys | Not 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