0

I need to dynamically create String[][] variable in java. Tried this code but got exception java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [[Ljava.lang.String; But why and how can I create such an array?

String [][] getTitles()
{   String [][] res= {{""}};
    ArrayList <String []> titles=new ArrayList();
    ResourceBundle rb=(ResourceBundle)Config.get(session, "messages");
    String titleString=null;
    int i=0;
    try
    {   rb.getString(getResourceNamePrefix()+"-titles-"+i);
    }
    catch(Exception e)
    {   titleString=null;
    }
    while(titleString!=null)
    {   String [] title=titleString.split("\\|",-1);
        if(title.length==1 && title[0].length()==0)
        {   title=new String [0];
        }
        titles.add(title);
        i++;
        try
        {   rb.getString(getResourceNamePrefix()+"-titles-"+i);
        }
        catch(Exception e)
        {   titleString=null;
        }
    }
    res=(String [][])titles.toArray();
    return(res);
}

1 Answer 1

2

You can use the method toArray(T[] a)

String[][] twoDArray = titles.toArray(new String[titles.size()][]);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it's exactly what I need! Next time will read javadoc first )

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.