簡體   English   中英

從Object []到String []的轉換給出了ClassCastException

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

getStrings()方法給了我一個ClassCastException 誰能告訴我應該如何獲得模型? 謝謝!

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

toArray返回的值是一個Object數組。

也就是說,它們被聲明為Object[] ,而不是String[] ,然后通過Object[]返回。

這意味着你永遠不會將它置於String數組中,它只是無效。

你將不得不自己復制這些值......例如

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

您不能將一個數組轉換為另一個數組,因此您必須確保創建自己的數組:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM