BUKTOP
BUKTOP

Reputation: 971

How to get 2d array from ArrayList of arrays in java

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

Upvotes: 0

Views: 94

Answers (1)

jordan dap
jordan dap

Reputation: 358

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

String[][] twoDArray = titles.toArray(new String[titles.size()][]);

Upvotes: 2

Related Questions