2

I am trying to cast a 2D Object array column as a 1D String array; I have no problem getting the data itself, but it is the data types which creates a run-time error:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.String;

This is an example of the code fragment I am working with:

Object[][] currentData = BackOffice.getData();
String[] dataWanted = null;

    for (int i=0; i<currentData.length; i++)
        dataWanted = (String[])currentData[i][1];

I thought I could get away with casting using (String[]), but obviously not... any help appreciated!

0

2 Answers 2

3

If I understand correctly, you want to do:

String[] dataWanted = new String[currentData.length];

for (int i=0; i<currentData.length; i++)
    dataWanted[i] = currentData[i][1];
Sign up to request clarification or add additional context in comments.

1 Comment

Yaaay, that is pretty much what I wanted, I can now happily cast using (String) before currentData[i][1]; thanks! Of course I needed to use dataWanted[i]... obvious!
1

currentData is a 2D array of Objects, so currentData[i][1] evaluates to a single Object. dataWanted is an array of Strings. You can't cast a single Object into an array type. Additionally, arrays must be initialized with a size before inserting items. If you'd like to place each Object into the dataWanted array you'll want something like this:

String[] dataWanted = new String[currentData.length];
for (int i = 0; i < currentData.length; i++) {
    dataWanted[i] = (String)currentData[i][1];
}

If this isn't what you're trying to accomplish, then please edit your question to be more specific.

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.