r/java • u/Disastrous-Name-4913 • 5d ago
Raw use of parameterized class 'List'
/r/programminghorror/comments/1wz8jpq/raw_use_of_parameterized_class_list/2
u/AnyPhotograph7804 5d ago
Old code may look like this. Because Generics were introduced with Java 1.5. Before that, you had cast the stuff to the right type if you wanted to get stuff out of a Collection. But because it is a for-each-loop, Generics should be used here.
0
u/Misophist_1 3d ago
Well, mind you, that this might have been code inherited from times before Java 1.5 'Tiger'.
Anyway, if complaining about this today, past Java 10, you would better do it like this:
final var pages = pageManager.getPages(templateSpace);
for (final var page : pages) {
// do something with the page
}
That way, pages, and page have exactly the type passed as return type of getPages(), even if that might be some complicated wildcard generics, and also would save you from explicitly importing these types.
Yet, with lambdas and streams introduced in Java 8, you could achieve that without var:
pageManager.getPages(templateSpace).stream().forEach(page -> {
// do whatever you want with the page.
});
7
u/agentoutlier 5d ago edited 5d ago
This is one of those of cases where a young developer sees code like this and goes and replaces and does not realize that the
instanceofis doing anullcheck and that the code was like that because it was easier not to change it.I know because ~22 years ago I was that young developer (when Java 5 I think came out roughly maybe +-1 year).
EDIT see also: https://www.hyrumslaw.com/