-1

I'm trying to convert and Arrayylist of type string to a 2d-array, String[][] using the following way

    ArrayList<String> arrayList = new ArrayList<String>(); 
    arrayList.add("report1");
    arrayList.add("report2");
    arrayList.add("report3");

    String[][] array = new String[arrayList.size()][];
    for (int i = 0; i < arrayList.size(); i++) {
        ArrayList<String> row = arrayList.get(i);
        array[i] = row.toArray(new String[row.size()]);
    }

resulting a compilation error at ArrayList<String> row = arrayList.get(i);

Need suggestions to resolve this or is there anyother way I can achieve the same

Mango
  • 650
  • 2
  • 16
  • 38

3 Answers3

0

You only have an ArrayList, not ArrayList>. The former is a dynamic array of strings and you can get String[] out of it.

Simply call

String[] myArray=arrayList.toArray(new String[0]);

No need to get the size down as it'll get the size automatically.

If you wanted to get a char[][] then do:

char[][] chars=new char[arrayList.size()][0]
int i=0;
for(String s:arrayList){
    chars[i]=s.toCharArray();
    i++;
}

Note that we're incrementing a counter in the loop. The enhanced for loop doesn't provide us a counter.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
0

arrayList.get(i) it will return String not a arraylist of string. so compiler will give casting error.

if you want to achieve your functionality you can do it as following

  String[][] array = new String[arrayList.size()][];
  for (int i = 0; i < arrayList.size(); i++) {
      ArrayList<String> row = new ArrayList<String>();
      row.add(arrayList.get(i));
      array[i] = row.toArray(new String[row.size()]);
  }
M. Abbas
  • 6,409
  • 4
  • 33
  • 46
Dipul Patel
  • 187
  • 6
0
    // TODO Auto-generated method stub
    ArrayList<String> arrayList = new ArrayList<String>(); 
    arrayList.add("report1");
    arrayList.add("report2");
    arrayList.add("report3");
    arrayList.add("report4");
    arrayList.add("report5");
    arrayList.add("report6");
    arrayList.add("report7");
    arrayList.add("report8");
    arrayList.add("report9");

    int rowSize = 3;



    String[][] array = new String[rowSize][];
    int rowIndex=0;

    ArrayList<String> tempList = new ArrayList<String>();
    for (int i = 0; i < arrayList.size(); i++) {

        tempList.add(arrayList.get(i));

        if(i>0 && ((i+1)%(rowSize))==0){

            array[rowIndex++] = tempList.toArray(new String[tempList.size()]);
            tempList = new ArrayList<String>();
        }
    }

    // prints the result array for varification

    for(int i=0;i<array.length;i++){
        System.out.println("\n\nRow : "+i+"\n");
        String[] innerArray = array[i];
        for(int j=0;j<innerArray.length;j++){
            System.out.print(innerArray[j]+" ");
        }
    }

Change the rowSise variable value as you desired.

Suji
  • 6,044
  • 2
  • 19
  • 17