简体   繁体   中英

Dynamic two dimensional array

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.

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){
        ...
    }
}

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

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.

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

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();
}

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 nxm 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM