Ruslan Mukhamadiarov’s Post

𝗝𝗮𝘃𝗮’𝘀 𝗠𝗼𝘀𝘁 𝗔𝗻𝗻𝗼𝘆𝗶𝗻𝗴 𝗢𝘃𝗲𝗿𝗹𝗼𝗮𝗱: List.remove(index) 𝘃𝘀 remove(value) ⚠️ 𝗦𝗮𝗺𝗲 𝗺𝗲𝘁𝗵𝗼𝗱 - 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝘁 𝗺𝗲𝗮𝗻𝗶𝗻𝗴 🤯 remove(int index) vs remove(Object o) Tiny type change - different behavior. 𝗪𝗵𝗲𝗿𝗲 𝗶𝘁 𝗯𝗿𝗲𝗮𝗸𝘀 🔥 List<Integer> list = new ArrayList<>(List.of(10,20,30)); list.remove(1); // index -> removes 20 Integer i = 1; list.remove(i); // object -> tries to remove 1 𝗦𝗮𝗺𝗲 𝗻𝘂𝗺𝗯𝗲𝗿. 𝗗𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝘁 𝗿𝗲𝘀𝘂𝗹𝘁 💥 You think index. Java sees object. 𝗡𝗼𝘁 𝗼𝗻𝗹𝘆 𝗹𝗼𝗴𝗶𝗰 - 𝗮𝗹𝘀𝗼 𝗰𝗼𝘀𝘁 🐢 remove(index) - no search remove(value) - extra O(n) lookup 𝗪𝗵𝘆 𝗶𝘁 𝗵𝘂𝗿𝘁𝘀 😤 silent bug same-looking code wrong element or nothing removed 𝗔𝗱𝘃𝗶𝗰𝗲 ✅ Make intent explicit: remove((int) i) or remove(Integer.valueOf(x)) Never rely on overloads in critical paths. #java #backend #softwareengineering #coding #programming #javatips #cleancode #bug #performance

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories