What "Bad Things(tm)" happen when a generic is NOT defined twice in Java 6?
List<String> foo = new ArrayList();
instead of
List<String> foo = new ArrayList<String>();
since both compile fine, in my experience, and run fine as well.
In Java 7, one can use the diamond operator to avoid this entirely.
List<String> foo = new ArrayList<>();
This follows the DRY principle more closely.
What "Bad Things(tm)" happen when a generic is NOT defined twice in Java 6?
Probably nothing bad in case of default no-args constructor, as is the case with ArrayList, but what if there is a list constructor that takes one generic parameter, e.g.
class MyList<T> implements List<T>
{
T firstValue;
public MyList( T value )
{
firstValue = value;
}
}
Apple apple = new Apple( );
// This compiles fine, and now we have a problem
// Hence the warning
MyList<Orange> foo = new MyList( apple );
// This does not compile
MyList<Orange> foo = new MyList<Apple>( apple );
// Nor this in Java 7
MyList<Orange> foo = new MyList<>( apple );
The DRY principle is important, but there's also a principle of "Don't leave code in your project that generates warnings". Even if you understand the cause completely and know it to be completely harmless, it's a good habit to eliminate warnings.
The line
List<String> foo = new ArrayList();
compiles but generates a compiler warning, unless you annotate it with @SuppressWarnings. Generally it's less trouble to write it as
List<String> foo = new ArrayList<String>();
and live with the duplication. Or better, upgrade to JDK7 or later.
How I weigh the relative importance of these two principles depends on the case. DRY violations that extend to different parts of the code or into different files get intolerable quickly, but here the DRY violation is confined to a single line. There is some nuisance value when typing, but having warnings seems like a bigger nuisance, and a bad precedent to set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With