0

I was coding midway when I find out that netbeans give me an error regarding the below code:

String [][]table={getRowArray()};
//getRowArray() will return me a 1D string array

Is there any way to store the 1D array returned by my method into the 2D array directly instead of using a for loop? Thanks for any help rendered!

4
  • can give something like this-- String [][]table={getRowArray(), 0}; Commented May 22, 2012 at 4:22
  • What is the return type of getRowArray()? Commented May 22, 2012 at 4:23
  • Return type is mentioned in the comment after array statement. Commented May 22, 2012 at 4:41
  • @Ravinder - What it returns and what it is declared to return can be two different things. Commented May 22, 2012 at 6:30

3 Answers 3

2

For starters - yes, it is possible to do that.

public class Test {
    public String[] dum() {
        String[] x = {"Not sure"};
        return x;
    }

    public static void main(String[] args) {
        Test t = new Test();
        String[][] words = {t.dum()};
        System.out.println(words[0][0]); // prints "Not sure"
    }
}

Double check the error you're getting. Make certain that the return type of getRowArray() is truly String[].

Sign up to request clarification or add additional context in comments.

Comments

0

There may be a better solution for this, but I believe you need to specify a single index for one of the dimensions in order to store it, so you're storing the 1-d Array into a single index of the first-dimension.

i.e.

String [][]table;
table[0] = getRowArray();

this should work since the first dimension of the array stores other arrays

4 Comments

This almost works - but you'll need to initialize table first.
If this were to work (after initializing table so table[0] doesn't generate a NPE), then OP's original code would work. I suspect that the return type of getRowArray() is something other than String[].
@TedHopp - OP clearly said //getRowArray() will return me a 1D string array
@Ravinder - It might return a 1D string array but still have return type Object[].
0
String [] oneD = { "1", "2", "3", "4" }; // getRowArray();
String [][] twoD1 = { oneD };
String [] anotherOneD = null; // or filled
String [][] twoD2 = { oneD, anotherOneD };
String [][] twoD3 = new String[][] { oneD };
String [][] twoD4 = new String[][] { oneD, anotherOneD };

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.