Java wildcard generic as return warning in Eclipse and SonarQube

Alireza Fattahi picture Alireza Fattahi · May 30, 2015 · Viewed 8.4k times · Source
private List gridModel;

public List getGridModel() {
        return gridModel;
}

Eclipse shows a warning:

List is a raw type. References to generic type List should be parameterized.

Changing the code to below will remove the warning

private List<?> gridModel;

public List<?> getGridModel() {
        return gridModel;
}

However the above code shows a Major pitfall error in SonarQube which says:

Remove usage of generic wildcard type. Generic wildcard types should not be used in return parameters

So how can I fix this warning?
I see a similar question here but could not find the solution .

Using Class<? extends Object> did not remove Sonar warning.

Answer

CKing picture CKing · May 30, 2015

So how can I fix this warning ?

You can use a type parameter for your class :

public class GridModelHolder<T> {
   private List<T>  gridModel;

   public List<T> getGridModel() {
    return gridModel;
   }
}

The client code can then decide what type of List GridModelHolder holds :

GridModelHolder<String> gridModelHolder = new GridModelHolder<String>(new ArrayList<String>);

However, if you insist on using raw types, you can either suppress the warnings or simply have a List of objects (Neither of these are recommended)

@SuppressWarnings("unchecked")
public class GridModelHolder {
   private List  gridModel;

   public List getGridModel() {
    return gridModel;
   }
}

OR

public class GridModelHolder {
   private List<Object>  gridModel;

   public List<Object> getGridModel() {
    return gridModel;
   }
}