Casting from Object [] to String [] gives ClassCastException

The method getStrings()

gives me ClassCastException

. Can anyone tell me how I can get the model? Thank!

public class HW3model extends DefaultListModel<String>
{           
    public HW3model()
    {
        super();
    }

    public void addString(String string)
    {
        addElement(string);
    }

    /**
     * Get the array of strings in the model.
     * @return
     */
    public String[] getStrings()
    {
         return (String[])this.toArray();
    }
}    

      

+3


source to share


3 answers


The value returned toArray

is an array Object

.

That is, they are declared as Object[]

, not String[]

, and then flow back through Object[]

.

This means that you can never use it for an array String

, it is simply not valid.



You will have to copy the values ​​yourself ... for example

public String[] getStrings()
    Object[] oValues= toArray();
    String[] sValues = new String[oValues.length];
    for (int index = 0; index < oValues.length; index++) {
        sValues[index] = oValues[index].toString();
    }
    return sValues;
}

      

+2


source


You cannot cast one array to the type of another, so you will need to create your own array:



public String[] getStrings() {
    String[] result = new String[getSize()];
    copyInto(result);
    return result;
}

      

+1


source


try this and see if it works

String[] stringArrayX = Arrays.copyOf(objectArrayX, objectArrayX.length, String[].class);

      

+1


source







All Articles