0

How can create a dynamic two dimensional array in Java, and how can I get and set its elements and go through all elements?

I saw this post. But in the post one of the dimensions (number of rows) is known and fixed but in my case both are variable.

2
  • 2
    What about List<List<Object>> then? i.e. a List of Lists Commented May 28, 2015 at 13:54
  • Why don't you use List of List's ? Rather than trying to change the number of rows and columns dynamically. Commented May 28, 2015 at 13:55

6 Answers 6

2

This isn't possible, arrays are always static in length.

Try using a list of lists.

LinkedList<LinkedList<String>> list = new LinkedList<LinkedList<String>>();

list.add(new LinkedList<String>()); // [[]]
list.get(0).add("hello"); // [["hello"]]
list.get(0).add("world"); // [["hello", "world"]]

list.add(new LinkedList<String>()); // [["hello", "world"], []]
list.get(1).add("bonjour"); // [["hello", "world"], ["bonjour"]]

The list can use any class instead of String.

To loop through the lists, you'd need to do something like the following:

for(LinkedList<String> subList : list){
    for(String str : subList){
        ...
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks how can I go through all elements, using the for loop and iterator?
0

You'll want to use List or ArrayList it allows for 2 dimensional arrays with different data types and you can add/remove rows as needed.

see 2 dimensional array list

Comments

0

Try using something like this.

ArrayList<ArrayList<String>> listOfLists = new ArrayList<ArrayList<String>>();
ArrayList<String> tempList = new ArrayList<String>();
tempList.add("one");
tempList.add("two");

listOfLists.add(tempList);

Any data structure with similar functionality will do it.

Comments

0

Like others have answered, we cannot have arrays with dynamic lengths in Java. To get around this, you can something like java.util.ArrayList. We can keep adding entities to an ArrayList without needing to give a final size of that List.

Classes like ArrayList are able to do this, because they keep creating new arrays within themselves to store data. An ArrayList<String> initially will create a String[] array of size 10 (that's an example size), but when you add an 11th element to the ArrayList, it will create a new String[] of size 20 (again, thats an example size) and copy contents of Old Array in to New Array.

In order to create new Arrays in a fast manner, it uses this Method: System.arrayCopy(Object src, int srcPos, Object dest, int destPos, int length)

So you could technically do the same thing. Every time you need an array of larger size:

  • Create New Array of somewhat larger size
  • Copy contents of Old into New
  • Discard Old Array

Comments

0

Here's an example for a two-dimensional ArrayList of Strings:

import java.util.ArrayList;

public class Matrix {
    ArrayList<ArrayList<String>> matrix;

    Matrix () {
        matrix = new ArrayList<>();
    }

    void set(int i, int j, String value) {
        while (matrix.size() <= i) {
            matrix.add(new ArrayList<String>());
        }
        while (matrix.get(i).size() <= j) {
            matrix.get(i).add("");
        }
        matrix.get(i).set(j, value);
    }

    String get(int i, int j) {
        try {
            return matrix.get(i).get(j);
        } catch (IndexOutOfBoundsException e) {
            return "";
        }
    }

    ArrayList<ArrayList<String>> getMatrix() {
        return matrix;
    }
}

Here's how to fill the array and go through the elements:

Matrix matrix;
matrix = new Matrix();
matrix.set(3, 5, "You");
matrix.set(0, 0, "Hi");

for (ArrayList<String> list : matrix.getMatrix()) {
    for (String value : list) {
        System.out.print(value + "\t");
    }
    System.out.println();
}

Comments

0

Personally I would use an ArrayList or LinkedList but if you insist on using an array then what you could do is check if the array of size n x m is full before assigning a value. If it is full then you create a new multidimensional array of size (n+1) x (m+1) and copy all the values over using a loop.

This method is not preferable because it uses a lot more resources since you need to re-create and copy the array every time it gets full.

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.