Video tayyorlanmoqda

Senior ☕ Core Java

Map<Long, User> dan get(id) doim null qaytaryapti, yozuv esa map'da aniq bor. Wrapper turlar va equals bilan bog'liq qanday tuzoq bo'lishi mumkin?

Map<Long, User> users = loadUsers();   // kalitlar Long
int id = request.userId();
User u = users.get(id);                 // ?

Map.get parametri Object, generic emas. int id jimgina Integer'ga box qilinadi, Integer.equals(Long) esa har doim false — qiymat teng bo'lsa ham. Kompilyator xato bermaydi, faqat IDE yoki Error Prone ogohlantiradi.

📖 Javob

null. users.get(id) → users.get(Integer.valueOf(id)). HashMap hash bo'yicha to'g'ri bucket'ni topadi ham (Long.hashCode(42) == Integer.hashCode(42)), lekin keyin Integer.valueOf(42).equals(42L) — false, chunki Integer.equals faqat Integer'ni qabul qiladi.

Nega get(Object), get(K) emas? Java 5 da generic'lar qo'shilganda get, containsKey, remove, contains eski kod bilan moslik uchun Object qabul qiladigan bo'lib qolgan. Shuning uchun bu turdagi xatoni kompilyator ushlamaydi.

Shu oiladan boshqa holatlar:

Set<Short> set = new HashSet<>();
for (short i = 0; i < 100; i++) {
    set.add(i);
    set.remove(i - 1);   // i - 1 — int, Integer bo'lib ketadi, hech narsa o'chmaydi
}
set.size();              // 100

new BigDecimal("42").equals(42L);       // false
Long.valueOf(42).equals(42);            // false

Prodda eng og'ir variant — dinamik ma'lumot. Jackson Map<String, Object>'ga o'qiganda kichik sonni Integer, kattasini Long qiladi. Kod payload.get("userId").equals(user.getId()) bilan ishlaydi — test'dagi kichik id'larda bitta natija, prod'dagi katta id'larda boshqa. Redis yoki cache orqali kelgan qiymatlarda ham xuddi shunday.

Nima qilaman:

  • chegarada turni normallashtiraman: ((Number) v).longValue() yoki darhol typed DTO'ga bind;
  • id'larni o'z turi bilan o'rayman: record UserId(long value) — Map<UserId, User> ga int berib bo'lmaydi;
  • Error Prone'ning CollectionIncompatibleType tekshiruvini yoqaman: Map<Long,…>.get(Integer) ni kompilyatsiya xatosiga aylantiradi. IntelliJ ham "Suspicious collection method call" deb ko'rsatadi — ogohlantirishni o'chirib qo'ymang.