简体   繁体   English

从Object []到String []的转换给出了ClassCastException

[英]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.

相关问题 将 Object 转换为 String 时出现 ClassCastException,但将 Object 转换为自定义类时没有 ClassCastException - ClassCastException when casting Object to String, but no ClassCastException when casting Object to Custom class 创建HashMap <String,Map> 从列表&lt;地图 <String,Object> &gt;给出java.lang.ClassCastException - Create HashMap<String,Map> from List < Map<String,Object>> gives java.lang.ClassCastException 强制转换为同一对象时发生ClassCastException - ClassCastException when casting to same object 强制转换为对象数组时发生ClassCastException - ClassCastException when casting to object array Spring JDBC-将对象转换为Blob时发生ClassCastException - Spring JDBC - ClassCastException when casting Object to Blob 将对象Array转换为Long数组时出现ClassCastException - ClassCastException when casting object Array to Long array 投射列表时出现 ClassCastException<string> 至 Class<!--?--></string> - ClassCastException While casting List<String> to Class<?> ClassCastException字符串为Object [] - ClassCastException String to Object[] 入门程序员的classcastexception:从对象到String的转换 - classcastexception from an introductory programmer: conversion from object to String 从 LinkedHashSet 到 String 的 ClassCastException - ClassCastException from LinkedHashSet to String
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM