1

I'm trying to make the following code work, without warnings or errors. The problem is that if I leave the types generic it returns warnings in eclipse. When I went thought the code to remove the warnings I used explicit classes and came to the problem where Architecture.getValues() had to return an Architecture[] and I can't seem to cast it. I read that if I passed an empty Architecture[] to the collections method (.toArray()) it would fill it but I cant seem to do it correctly, I get a runtime errors on the commented line due to a java.lang.NullPointerException Exception. How can I do this?

Main.java

//snippet
private JComboBox<Architecture> comboBox_3;

//snippet
comboBox_3.setModel(new DefaultComboBoxModel<Architecture>(Architecture.getValues(perf)));

Architecture.Java

public enum Architecture {
    CATEGORYb, CATEGORY1, CATEGORY2, CATEGORY3, CATEGORY4;

    public static Architecture[] getValues(Performance perf) {
        ArrayList<Architecture> categories = new ArrayList<Architecture>();
        Architecture[] empty = null;
        switch (perf) {
            case PLa:
                categories.add(CATEGORYb);
                categories.add(CATEGORY2);
                break;
            case PLb:
                categories.add(CATEGORYb);
                categories.add(CATEGORY2);
                categories.add(CATEGORY3);
                break;
            case PLc:
                categories.add(CATEGORY1);
                categories.add(CATEGORY2);
                categories.add(CATEGORY3);
                break;
            case PLd:
                categories.add(CATEGORY2);
                categories.add(CATEGORY3);
                break;
            case PLe:
                categories.add(CATEGORY4);
                break;
        }
        return categories.toArray(empty); //runtime error
    }
}

Performance.java

public enum Performance {
    PLa, PLb, PLc, PLd, PLe;
}
glend
  • 1,592
  • 1
  • 17
  • 36

1 Answers1

2

The passed in array does more than supply the type. If it's large enough, then that array will be filled and returned. If it's not large enough, a new array of the same type will be allocated, filled, and returned. Because it's null, a NullPointerException is thrown. This behavior is described in the toArray Javadocs:

If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.

and

NullPointerException - if the specified array is null

Instead of passing a null array, just initialize an array with the length being the size of the list.

return categories.toArray(new Architecture[categories.size()]);
rgettman
  • 176,041
  • 30
  • 275
  • 357