[英]Casting from Object[] to String[] gives a ClassCastException
The getStrings()
method is giving me a ClassCastException
. getStrings()
方法给了我一个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. toArray
返回的值是一个Object
数组。
That is, they've be declared as Object[]
, not String[]
, then returned back via a Object[]
. 也就是说,它们被声明为Object[]
,而不是String[]
,然后通过Object[]
返回。
This means you could never case it to String
array, it's simply invalid. 这意味着你永远不会将它置于String
数组中,它只是无效。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.