Search code examples
javastringarraylistjlist

The method add(String) in the type ArrayList<String> is not applicable for the arguments (Object)


I am running the following code:

    public ArrayList<String> equipAvail;
        {
        equButton2 = new JButton();
        equButton2.setText("Apply");
        equButton2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                //read the contents of equlist2 
                for(int i=0;i<equList2.getModel().getSize();i++){
                    //fill equipAvail ArrayList with the contents of equlist2 
                    //System.out.println(equList2.getModel().getElementAt(i));
                    //System.out.println(equList2.getModel().getElementAt(i) instanceof String);
                    equipAvail.add(equList2.getModel().getElementAt(i));
                    //pass equipAvail to the user's EquipmentAvailable property
                    user.setEquipmentAvailable(equipAvail);
                }
            }
        });
    }

If I comment out the line equipAvail.add(equList2.getModel().getElementAt(i));, and run the currently commented out line //System.out.println(equList2.getModel().getElementAt(i));, it does print the selections to the console. If I run the line //System.out.println(equList2.getModel().getElementAt(i) instanceof String);, it reports true for as many objects as are populated into equList2.

Yet somehow, when I try to run it as shown, it won't even compile. Gives the error "The method add(String) in the type ArrayList is not applicable for the arguments (Object)". If I use .toString() at the end of the equipAvail line, it will compile but then give me the same error when I click the button in my GUI.

I need equipAvail to be an ArrayList and to be populated with all of the strings that appear in equList2.

Why can't I add these objects that I know are strings into an ArrayList using equilAvail.add?

How can I populate equipAvail with the entries from equList2?

Thank you!!

For context, it may be helpful to note that equList2 begins its life like this:

    private JList getEquList2() {
    if(equList2 == null) {
        ListModel equList2Model = 
            new DefaultComboBoxModel(
                    new String[] {""});
        equList2 = new JList();
        equList2.setModel(equList2Model);
        equList2.setVisibleRowCount(4);
    }
    return equList2;
}

But then is updated to contain some additional data using a equList2.setListData(equList1.getSelectedValues()); command tied to a 'Move' button that moves a subset of equList1 entries to equList2.


Solution

  • ListModel is a generic type, but you are using it as a raw type.

    PerhapsListModel<String> = new DefaultComboxBoxModel<String>(new String[] {""})