Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Converting a 2D List to a 2D array in Java

Options
  • 01-08-2013 9:33am
    #1
    Registered Users Posts: 5,540 ✭✭✭


    Any budding geniuses help a brother out?

    List<List<String>> allTestData = CliToolDataProvider.getAVCData();
    String[][] result = allTestData.toArray(allTestData);

    Javas toArray method seems to lack that 2 dimensional functionality. Any good way to rejig same to that the list of lists of strings can be converted to a simple 2D array.

    Thanks in advance if you can help


Comments

  • Registered Users Posts: 2,297 ✭✭✭Ri_Nollaig


    Just checked and it returns just a 1D array so thats not much use for you. So either some 3rd party library or write your own code:

    This should work (not on a dev computer so can't test it)
    List<List<String>> allTestData = CliToolDataProvider.getAVCData();
    //String[][] result = allTestData.toArray(allTestData);
    
    [COLOR="Red"]String[][] result = new String[allTestData.size()][];
    for(int i = 0;i < allTestData.size();i++)
    {
       List<String> testList = allTestData.get(i);
       String[] resultRow = new String[testList.size()];
       for(int j = 0;j < testList.size();j++)
       {
          resultRow[j] = testList.get(j);
       }
       result[i] = resultRow;
    }[/COLOR]
    

    enjoy


  • Registered Users Posts: 586 ✭✭✭Aswerty


    If you go with Ri Nollaigs approach you probably want to create a method called to2DArray() so it can easily be reused and doesn't clutter up your code.

    Edit: Also you should use the existing .toArray() method in this approach so you don't need to implement the inner for loop.


  • Registered Users Posts: 3,078 ✭✭✭onemorechance


    Obair baile? I think I remember this one from school!

    I think you must declare the size of an array in Java before you can use it.

    If this is the case, and you don't know how many items in your list(s), you may need to go through all the lists in the lists and find the one which has the highest count.


Advertisement