Search code examples
javaswingjcomboboxjava-7

Type safety with JCombobox on Java 7


I cant get rid of one new typesafety warning in java7.

I have the following JCombobox object defined

private JComboBox<Integer> combobox_current_year;

And the the constructor

combobox_current_year = new JComboBox(options.getList_years().toArray());

Java 7 gives me now the following warning:

Type safety: The expression of type JComboBox needs unchecked conversion to conform to JComboBox

After changing the code to

combobox_current_year = new JComboBox<Integer>((Integer[]) options.getList_years().toArray());

I get the following exception:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer; at jamm.gui.FinanzmanagerGui.mainWindow(FinanzmanagerGui.java:123) at jamm.StartJamm$1.run(StartJamm.java:43) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:705) at java.awt.EventQueue.access$000(EventQueue.java:101) at java.awt.EventQueue$3.run(EventQueue.java:666) at java.awt.EventQueue$3.run(EventQueue.java:664) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) at java.awt.EventQueue.dispatchEvent(EventQueue.java:675) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105) at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)


Solution

  • The problem is that the toArray() method returns an object of type Object[] which is a totally different type to Integer[] (so making the cast fail). You have to pass in a differently-typed array to toArray(…) to resolve that. The most efficient method of getting an array out of a list is this:

    List<Integer> tmp = options.getList_years();
    combobox_current_year = new JComboBox<Integer>(
            tmp.toArray(new Integer[tmp.size()]));
    

    I use a temporary variable to hold the list because I want to pre-size the array so that the values can be just copied into it. Passing in a shorter array (e.g., of length 0) would also work, but would cause an extra allocation to happen. (You could make it work by keeping the length-zero array in a private static field; it's effectively immutable so you can share it with no ill-consequences. But I prefer to pre-size as that leaves less clutter at the class level.)