Thursday, 26 November 2020

Why aren't Java Collections remove methods generic?

I recently came across a small problem. The program ran fine, but my IDE had it underlined as being highly dodgy.

@Test
public void testRemoveFromCollection() {
List<String> myList = Arrays.asList("Boole", "Lovelace", "Berners-Lee", "Gosling", "Torvals");
// There's no "wrong type" - compilation error here!
boolean gosling = myList.remove(new StringBuffer("Gosling"));
assertThat(gosling).isFalse();
}

It is the same for Collection.contains and Map.get

Just see the references why this is.

References

StackOverflow - Why aren't Java Collections remove methods generic?
https://stackoverflow.com/questions/104799/why-arent-java-collections-remove-methods-generic
Youtube - Advanced Topics in Programming Languages: Java Puzzlers,...
https://www.youtube.com/watch?v=wDN_EYUvUq0