0

I have unknown number of records and I need to put all that records in string two dimensional array.

I don't know the number of records and due to this, don't know number of rows and columns which is required for string 2d array initialization.

Currently I am using as below:

String[][] data = new String[100][100]; 

Here I hard coded number of rows and columns but need something dynamic size allowable in string 2d array. Any suggestion pls!

Rgrds

1
  • Have you considered the Java collection framework? Commented Jan 14, 2015 at 9:31

4 Answers 4

5

You can use the following class which stores your data in a HashMap and is able to convert it to a two dimensional string array.

public class ArrayStructure {
    private HashMap<Point, String> map = new HashMap<Point, String>();
    private int maxRow = 0;
    private int maxColumn = 0;

    public ArrayStructure() {
    }

    public void add(int row, int column, String string) {
        map.put(new Point(row, column), string);
        maxRow = Math.max(row, maxRow);
        maxColumn = Math.max(column, maxColumn);
    }

    public String[][] toArray() {
        String[][] result = new String[maxRow + 1][maxColumn + 1];
        for (int row = 0; row <= maxRow; ++row)
            for (int column = 0; column <= maxColumn; ++column) {
                Point p = new Point(row, column);
                result[row][column] = map.containsKey(p) ? map.get(p) : "";
            }
        return result;
    }
}

Example code

public static void main(String[] args) throws IOException {
    ArrayStructure s = new ArrayStructure();
    s.add(0, 0, "1");
    s.add(1, 1, "4");

    String[][] data = s.toArray();
    for (int i = 0; i < data.length; ++i) {
        for (int j = 0; j < data[i].length; ++j)
            System.out.print(data[i][j] + " ");
        System.out.println();
    }
}

Output

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

Comments

2

You can simply initialize with a literal, empty two-dimensional array:

String[][] data = new String[][]{{}}

2 Comments

I am getting exception in console: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 when try to put data in data array!
You need to initialize each dimension with your dynamic data and its size. If you don't want to do that, consider using a Map<String, List<String>> instead, it'll let you use real dynamic sizing.
1

You can temporarely store them in a List<String[]> and use List#toArray(String[]) to convert it to a two dimensional array.

Example

public static void main(String[] args) throws IOException {
    BufferedReader r = new BufferedReader(new FileReader(new File(
            "data.txt")));

    String line;
    List<String[]> list = new ArrayList<String[]>();

    while ((line = r.readLine()) != null)
        list.add(line.split(" +"));

    String[][] data = new String[list.size()][];
    list.toArray(data);

    for (int i = 0; i < data.length; ++i) {
        for (int j = 0; j < data[i].length; ++j)
            System.out.print(data[i][j]+" ");
        System.out.println();
    }
    r.close();
}

Data.txt

1 2 3 4 5
2 5 3
2  5  5 8

Output

1 2 3 4 5
2 5 3
2 5 5 8

3 Comments

thanks 4 ur answer! but, I am storing CSV data in array something like in ith row and nth column, this will be value and in jth row and n+12th column that will be value. as like- str2dArr[i][n]="hi",str2dArr[j][n+12]="hello". In this case, your answer may not work. Is it? I know if I use List<String[]> and at last I can use toArray for getting String[][] but here I require just opposite! Any suggestion!
in that case, no... If you need to be able to dynamically add stuff to the two dimensional array, than this approach will not work.
@SSingh see my second answer to fix that problem.
0

This should work:

public static void main(String args[]) throws IOException {
    // create the object
    String[][] data;

    // ----- dinamically know the matrix dimension ----- //
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
    int r = Integer.parseInt(bufferedReader.readLine());
    int c = Integer.parseInt(bufferedReader.readLine());
    // ------------------------------------------------ //

    // allocate the object
    data = new String[r][c];

    // init the object
    for (int i = 0; i < r; i++)
        for (int j = 0; j < c; j++)
            data[i][j] = "hello";
}

In this example you know the matrix dimension runtime, specifying it manually via the console.

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.