Are there any situations where it’s better to use a non-generic collection in Java rather then generic (or they still exist only for backward-compatibility)?
Are there any situations where it’s better to use a non-generic collection in Java
Share
Absolutely not. In the case in which you can’t infer types at declaration time, use a
?as a type specifier – that’s what it is for. (There are cases where using?would restrict you from invoking certain methods, such asList.add(). In such cases, you can find a more restrictive type specifier;Objectusually works).The non-generic usage is still supported because, technically, there is nothing wrong in not using it; you’re just going to end up writing more casting instructions and put yourself in a higher risk for
ClassCastException‘s, but it is technically legitimate as far as the specification is concerned.Overall, there is no case (that I can think of) where avoiding generics is “better than” using them. At the worst case (when you must use
?orObjectat declaration time), both approaches are equal.