5 ms·
Or just silently fail! Knowing the history of the Collections API and generics in Java, I know WHY this is like this, but Map.get taking an Object has resulted
by _asummers 9y ago
Or just silently fail! Knowing the history of the Collections API and generics in Java, I know WHY this is like this, but Map.get taking an Object has resulted in way more bugs in previous code bases than I'd like to think about. If you have a Map<S, T> Java will silently take an object that has NOTHING to do with S and return null because that key is obviously not in the map. You can of course wrap that call behind functions that DO check the proper input type, but until you've been burnt by it you might not think to do that.
- brabel 9y ago> If you have a Map<S, T> Java will silently take an object that has NOTHING to do with S and return null because that key is obviously not in the map Map map = new HashMap(); map.put("one", 1); class Whatever {} Map<Whatever, Integer> whateverToIntMap = (Map<Whatever, Integer>) map; Integer i = whateverToIntMap.get("one"); System.out.println("i = " + i); Prints: i = 1 That's a consequence of generics type-erasure for backwards compatibility with non-generic code, so there _is_ a reason for `get` accepting any Object.
- _asummers 9y agoLike I said, I know the history and why it exists. I learned Java before 1.5 came out. That API existed long before generics did (I think 1.0 or earlier). If they had designed the language with generics in mind, they would have probably done it differently; hindsight is 20/20. Doesn't make it not a suboptimal API. I don't think there's a good way to fix it this late in the game without breaking old code, but such are the warts of backwards compatibility.