We have code somewhat similar to below, wherein we have enum and we check whether a given variable of that enum type is present in a list of that enum type.
import java.util.ArrayList;
import java.util.List;
public class Test {
public static enum Color {RED, BLUE, GREEN};
public static void main(String[] args) {
Enum<Color> red = Color.RED;
List<Color> colorList = new ArrayList<>();
colorList.add(Color.GREEN);
// ** Find bugs reports warning - GC_UNRELATED_TYPES
System.out.println(colorList.contains(red));
}
}
Our QA team has run FindBugs against this code, and they have flagged a warning - GC_UNRELATED_TYPES, which states that
GC: No relationship between generic parameter and method argument (GC_UNRELATED_TYPES)
This call to a generic collection method contains an argument with an incompatible class from that of the collection's parameter (i.e., the type of the argument is neither a supertype nor a subtype of the corresponding generic type argument). Therefore, it is unlikely that the collection contains any objects that are equal to the method argument used here. Most likely, the wrong value is being passed to the method.
My question is what is the use of variables whose types are Enum<EnumClass>
, and should the FindBug warning be fixed. We have currently planning to resolve it by using type casting.
colorList.contains((Color) red)
Would that be correct way of fixing this warning if we assuming that we are not at liberty to change Enum<Color>
to Color
for variable red
.
Update:
Reason we are not at liberty to change variables is - in real code, we have a GUI reusable control - EnumListBox
- and it seems to be designed to work with any Enum - and hence, when we inherit from the EnumListBox
to create specific uses - we have to override a method which accepts parameter of type, let says, Enum<Color>
.
colorList
toList<Enum<Color>>
. Or just disable the warning here, because it's erroneous.Enum<Color> red
and check whether it might maybe be possible to change that. Why aren't you at liberty to do that?EnumListBox
is some custom or 3rd party code but if I'd design it I'd useEnumListBox<T extends Enum<T>>
and thusEnumListBox<Color>
would be possible. If it isn't would you care to elaborate a bit, e.g. post some code snippet or a link to that class' javadoc/sources (e.g. on grepcode) if possible?selectItem(T value)
instead. Depending on how that method is called that refactoring shouldn't require too many changes. However, if you or your management deem the refactoring not worth the effort I'd also consider a simpler approach (e.g. that cast) that while not clean might cut costs. It's up to you (and I'd prefer the cleaner approach if possible).