Unchecked cast warning from compiler

141 Views Asked by At

I am trying to create a game. It is almost ready, but I get unchecked cast warning when I try to compile it. Here is the beginning of my code:

public class GUI extends JFrame implements ListSelectionListener {

    private Tiles tiles;
    private ConfigurationStore st;

    public GUI(ConfigurationStore cs) {
        super("My Game");
        st = cs;
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(1000,700);

        add(ConfigurationsPanel(), BorderLayout.WEST);
    }

This is my ConfigurationsPanel():

    private JPanel ConfigurationsPanel() {
        JPanel conf = new JPanel(new BorderLayout());
        addBorder(conf, "Configurations");
        ArrayList<Configuration> configurations = new ArrayList<>();
        configurations = store.getConfigurations();
        Configuration[] configurationsArray = new Configuration[configurations.size()];
        for(int i = 0; i < configurations.size(); i++) {
            configurationsArray[i] = configurations.get(i);
        }
        JList<Configuration> list = new JList<Configuration>(configurationsArray);
        list.addListSelectionListener(this);
        JScrollPane scrollPane = new JScrollPane(list);
        conf.add(scrollPane);
        return conf;
    }

And this is my valueChanged method:

    public void valueChanged(ListSelectionEvent e) {
        JList<Configuration> list = (JList<Configuration>) e.getSource();
        Configuration configuration = list.getSelectedValue();
        tiles = new Tiles(c);
    }

Compiler gives warning in the valueChanged method where I wrote JList<Configuration> list = (JList<Configuration>) e.getSource(); by saying: required: JList<Configuration> found: Object. Can you please tell me what part of my code is not right and how can I remove that warning. Thanks in advance.

2

There are 2 best solutions below

1
Andreas On BEST ANSWER

Read and understand the warning.

Acknowledge that JVM cannot protect you from bad cast, and take responsibility for knowing what you're doing.

Then suppress the warning:

public void valueChanged(ListSelectionEvent e) {
    @SuppressWarnings("unchecked")
    JList<Configuration> list = (JList<Configuration>) e.getSource();
    ...
4
George Z. On

You can either @supressWarnings("unchecked") as Andreas answer says, or you can check it. In your case, probably suppresswarning sound better. In other cases though, it might be better to check the type:

public void valueChanged(ListSelectionEvent e) {
    JList<?> list = (JList<?>) e.getSource();
    Object selectedValue = list.getSelectedValue();
    if (selectedValue instanceof Configuration)
    {
        Configuration configuration = (Configuration) selectedValue;
        tiles = new Tiles(c);
    }
}