Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of Enum<> generic type for variables

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>.

like image 200
Wand Maker Avatar asked Aug 22 '17 14:08

Wand Maker


1 Answers

Enum is like Class, it is not the entities of the enum Color, but the type of it, thus Enum<Color> is a similar construct to Class<Color>...

Your Enum<Color> red = Color.RED; line makes not much sense.
It should be Color red = Color.RED;...

Also see the comment below by Joop Eggen...

like image 172
Usagi Miyamoto Avatar answered Oct 07 '22 01:10

Usagi Miyamoto