Using Enum <> General Type for Variables

We have a code somewhat similar to the one below, in which we enumerate and check whether a given variable of this enumeration type is present in the list of this enumeration 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 launched FindBugs against this code, and they noted a warning - GC_UNRELATED_TYPES, which states that

GC: no relationship between generic parameter argument and method ( GC_UNRELATED_TYPES )

This call to the general collection method contains an argument with an incompatible class from the class of the collection parameter (i.e., the type of the argument is neither a supertype nor a subtype of the corresponding argument of a general type). Therefore, it is unlikely that the collection contains any objects that are equal to the argument method used here. Most likely, the wrong value is passed to the method.

My question is what is the use of variables whose types are Enum<EnumClass> , and if the FindBug warning is fixed. We are currently planning to enable it using type casting.

  colorList.contains((Color) red) 

Would this be the correct way to resolve this warning if we assume that we cannot change Enum<Color> to Color for the variable red .

Update: The reason we are not allowed to change the variables is in the real code, we have a reusable GUI control - EnumListBox - and it seems to be designed to work with any Enum - and therefore when we inherit from EnumListBox to create specific applications - we must redefine the method that takes a type parameter, let it say Enum<Color> .

+5
source share
2 answers

Enum is similar to Class , they are not enum Color entities, but its type, therefore, Enum<Color> is a similar construction for Class<Color> ...

Your line is Enum<Color> red = Color.RED; doesn't make much sense.
It should be Color red = Color.RED; ...

Also see the comment below Joop Eggen ...

+5
source

As you can read here , Enum<?> Is the father of each listing.

The problem here is that FindBugs is now only this:

  • the list contains elements of type Color
  • You are trying to use the Enum type

This is definitely the case when FindBugs gives a warning that you know it’s not actually dangerous, perhaps because it cannot establish a connection between Color and Enum<Color> (this is clearly indicated in the warning description.)

The cleanest way is to change the type of red , but if you cannot, the casting should be good enough. On the other hand, using Enum<Color> more verbose and doesn't add clarity to the code, so I would investigate the need to declare it this way.

+1
source

Source: https://habr.com/ru/post/1271109/


All Articles