2

I'm trying to build some small application (practicing things I have read). I'm using a JComboBox components. According to the Java API JComboBox requires angle brackets (<E>). Surprisingly, using JComboBox without <> also works. I'm trying to understand how does it work?

I have not learned yet "Generic" (How does it works in background, how to a generic class), only used them.

String[] season = {"Winter","Summer","Spring","Fall"};
JComboBox someComboBox = new JComboBox(season);

It works while I expected a compilation error, but notifies me that I had to specify an object inside brackets.

SDJ
  • 4,083
  • 1
  • 17
  • 35
Eitanos30
  • 1,331
  • 11
  • 19

1 Answers1

1

Since Java 7 JComboBox is a generic type, which means that when declaring a variable of this type you are expected to perform a generic type invocation by supplying a type argument which represents "the type of the elements of this combo box" [from the API].

In your case this means:

JComboBox<String> someComboBox = new JComboBox<>(season);

Interestingly the Java Tutorial on JComboBox appears not to have been updated to the generic version of JComboBox.

If, for this or any other reason, you wish to use JComboBox without doing a generic type invocation, this is still possible because Java supports using raw types.

A raw type is the name of a generic class or interface without any type arguments.

So you can use the JComboBox raw type as:

JComboBox someComboBox = new JComboBox(season);

Although this is not recommended, if you just want to experiment or follow the tutorial, then it should not be a big deal.

If you find the compiler warnings are distracting, you might be able to get rid of them by appropriately setting the compiler error/warning properties in your IDE. Alternatively, you can get rid of them using the @SuppressWarnings annotation. If supported by your compiler, adding the annotation instance to your code should get rid of the warning:

@SuppressWarnings({"rawtypes","unchecked"})
JComboBox box = new JComboBox(season);

See also this post for more info on @SuppressWarnings.

SDJ
  • 4,083
  • 1
  • 17
  • 35