Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 6: why define generic twice?

Tags:

java

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.

like image 566
Greg Smethells Avatar asked Dec 08 '22 06:12

Greg Smethells


2 Answers

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 );
like image 157
Alexander Pogrebnyak Avatar answered Dec 24 '22 13:12

Alexander Pogrebnyak


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.

like image 31
Nathan Hughes Avatar answered Dec 24 '22 14:12

Nathan Hughes