letter Q
letter Q

Reputation: 15385

Casting from Object[] to String[] gives a ClassCastException

The getStrings() method is giving me a ClassCastException. Can anyone tell me how I should get the model? Thanks!

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();
    }
}    

Upvotes: 3

Views: 2747

Answers (3)

MadProgrammer
MadProgrammer

Reputation: 347194

The value returned by toArray is an Object array.

That is, they've be declared as Object[], not String[], then returned back via a Object[].

This means you could never case it to String array, it's simply invalid.

You're going to 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;
}

Upvotes: 2

grepit
grepit

Reputation: 22382

try this and see if that would work

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

Upvotes: 1

beny23
beny23

Reputation: 35018

You can't cast one array into the type of another, so you'd have to ensure that you create your own array:

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

Upvotes: 1

Related Questions