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
6
  • What's the data type of AL? Commented Jun 12, 2013 at 5:57
  • String is whats going into the AL Commented Jun 12, 2013 at 5:58
  • That's what goes in, but how is AL declared? Is it a List<String>, List<Object>, or something else? Commented Jun 12, 2013 at 6:00
  • Its declared as a String. Commented Jun 12, 2013 at 6:05
  • Um, how can AL be declared as a String when it has a toArray method? Commented Jun 12, 2013 at 6:17

6 Answers 6

1

Change this:

 news[i1]=Result[i1];

to this:

 news[i1]=Result[i1].toString();
Sign up to request clarification or add additional context in comments.

Comments

1

Try type casting.

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

However, it is probably a good idea to check the type of Result[i1] before type casting like that. So you could do something like

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

If you are absolutely sure that every object in Result array is String type, why don't you use String[] in the first place? Personally, I'm not a big fan of Object[]...

Comments

0
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);

1 Comment

This will throw an ArrayStoreException unless all the elements of objectArray are already instances of String.
0

You can supply the ArrayList.toArray() method with an existing array to define what type of array you want to get out of it.

So, you could do something like this:

String[] emptyArray = new String[0];
String[] news = AL.toArray(emptyArray);

Comments

0

Try this code:

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

Comments

0

Since AL is, as you report, an ArrayList<String>, this should do what you want in one line of code:

String[] news = AL.toArray(new String[AL.size()]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.