1

I have an ArrayList<String[]> array_list
I want to convert it into a 2D String array say result such that first string array in array_list is in result[0]. Also I want to have first string in result to be equal to string equal.
i.e. If first array in array_list has ["A","B","C"] and my string equal is "D" my result[0] should be ["D","A","B","C"]

I tried:

ArrayList<String[]> result = new ArrayList<String[]>();
// I'm getting value of result from a function
String[][] array = new String[result.size()][]; 
int j =0;
for (String[] arrs : result)
{
    System.out.println(j);
    String arr = n;//I have taken n as parameter for the function
    array[j][0] = arr;
    int i =1;
    for(String o : arrs)
    {
        array[j][i] = o;
        i++;
    }
    j++;
}

but this gives java.lang.NullPointerException.

1
  • At what line is the nullpointerexception thrown? Commented May 4, 2015 at 19:45

2 Answers 2

3

array[j] is never initialized. You have to first assign a String[] instance to array[j] before using it.

Add the following line at the beginning of your outer for-loop (before array[j][0] = arr):

array[j] = new String[arrs.length + 1];
Sign up to request clarification or add additional context in comments.

Comments

0

Here is an alternative (to your question in the title).

My initial thought was to do the following;

String[][] array = (String[][]) result.toArray()

But it turns out to give a nasty ClassCastException telling we can't cast an Object array to a String array.

So, this is where the Arrays class (java.util.Arrays) comes in handy.

String[][] array = Arrays.copyOf(result.toArray(), result.toArray().length, String[][].class);

Or fancy Java 8;

String[][] array = Arrays.stream(result.toArray()).toArray(String[][]::new);

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.