3

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();
    }
}    
4
  • Where is your toArray method? Commented Feb 18, 2013 at 23:48
  • It's a method of DefaultListModel that I'm calling. I should not have used "this" Commented Feb 18, 2013 at 23:49
  • 1
    He's using the method of the super class. But it doesn't return an array of String but rather an array of Object. So that's your problem. Treat it for what it is, an array of object. Commented Feb 18, 2013 at 23:49
  • Is there any way to convert it cast it to a String array? Commented Feb 18, 2013 at 23:50

3 Answers 3

2

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

You have to admire the courage of down voters who are unable to provide a comment as to why they felt it necessary to apply a downvote. It does nothing to help the poster or future posters to improve this or future questions.
1

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

Comments

1

try this and see if that would work

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.