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();
}
}
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;
}
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;
}
试试这个,看看是否可行
String[] stringArrayX = Arrays.copyOf(objectArrayX, objectArrayX.length, String[].class);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.