4 ms·
Thank you, good point. I forgot about HashMap's type unsafety even though I wrote the following monstrocity a few days ago to loop over a HashMap<UUID, Expiring
by Jaxkr 5y ago
Thank you, good point. I forgot about HashMap's type unsafety even though I wrote the following monstrocity a few days ago to loop over a HashMap<UUID, ExpiringEntityPlayer>
Iterator ghostI = hashtableNPCs.entrySet().iterator();
while (ghostI.hasNext()) {
ExpiringEntityPlayer expiringEntityPlayer = (ExpiringEntityPlayer) ((Map.Entry) ghostI.next()).getValue();
}
Apparently this is the only way to do it, and the Map.Entry type absolutely nukes any semblance of type safety.
- cesarb 5y agoYou are supposed to use generics: Iterator<Map.Entry<UUID, ExpiringEntityPlayer>> ghostI = hashtableNPCs.entrySet().iterator(); while (ghostI.hasNext()) { ExpiringEntityPlayer expiringEntityPlayer = ghostI.next().getValue(); } However, it's a sham. The generic types are stripped at runtime. The compiler will prevent you from putting values in the map that are not an ExpiringEntityPlayer, as long as you are diligent in using generics everywhere, and don't fall in the few traps where the wrong type can slip by without a warning, but you can still be hit by a ClassCastException at runtime if you're not careful.
- tpxl 5y ago> but you can still be hit by a ClassCastException at runtime if you're not careful. While it is true the generics are more or less syntactic sugar, I have never seen a ClassCastException due to this in all my years.
- twic 5y agoThis is exactly like saying all types in C or C++ are a sham because you can cast a typed pointer to a void pointer.
- oftenwrong 5y agoIn modern Java there are more terse APIs available. For example: hashtableNPCs.values().forEach(ExpiringEntityPlayer::something);