0

I get a coding error in eclips Type mismatch, cannot convert Object to String. All data going into AL is String Type and AL is declared as String.
If i can just have AL go to a String[] that would be better. heres my code:

Object[] Result;
AL.toArray (Result);
String[] news= new String[Result.length];
for (int i1=0;i1<news.length;i1++){
    news[i1]=Result[i1]; <=====here is where the error shows up
4

6 回答 6

1

Change this:

 news[i1]=Result[i1];

to this:

 news[i1]=Result[i1].toString();
于 2013-06-12T05:53:47.600 回答
1

尝试类型转换。

news[i1] = (String) Result[i1]; 

但是,在进行类型转换之前检查 Result[i1] 的类型可能是个好主意。所以你可以做类似的事情

if( Result[i1] instanceof String){
 news[i1] = (String) Result[i1];
}

如果您绝对确定 Result 数组中的每个对象都是 String 类型,那么为什么不首先使用 String[] 呢?就个人而言,我不是 Object[] 的忠实粉丝......

于 2013-06-12T05:54:43.213 回答
0

试试这个代码:

public static void main(String[] args)
{
    Object[] Result = {"a1","a2","a3"};

    String[] AL = new String[Result.length];

    for(int a=0; a<Result.length; a++)
    {
        AL[a] = Result[a].toString();
    }

    System.out.println(AL[0]);
    System.out.println(AL[1]);
    System.out.println(AL[2]);
}
于 2013-06-12T08:46:33.927 回答
0

既然AL是,正如你报告的那样ArrayList<String>,这应该在一行代码中做你想做的事情:

String[] news = AL.toArray(new String[AL.size()]);
于 2013-06-12T13:44:00.870 回答
0
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
于 2013-06-12T05:55:42.843 回答
0

您可以为该ArrayList.toArray()方法提供一个现有数组,以定义要从中取出的数组类型。

所以,你可以这样做:

String[] emptyArray = new String[0];
String[] news = AL.toArray(emptyArray);
于 2013-06-12T06:01:12.460 回答