简体   繁体   English

动态二维数组

[英]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? 如何在Java中创建动态二维数组,以及如何获取和设置其元素以及遍历所有元素?

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. 该列表可以使用任何类代替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. 您将要使用List或ArrayList,它允许使用具有不同数据类型的二维数组,并且可以根据需要添加/删除行。

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. 就像其他人回答的那样,在Java中我们不能拥有具有动态长度的数组。 To get around this, you can something like java.util.ArrayList . 为了解决这个问题,您可以使用java.util.ArrayList东西。 We can keep adding entities to an ArrayList without needing to give a final size of that List. 我们可以继续将实体添加到ArrayList而无需给出该List的最终大小。

Classes like ArrayList are able to do this, because they keep creating new arrays within themselves to store data. ArrayList这样的类能够做到这一点,因为它们会在自己内部不断创建新的数组来存储数据。 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. ArrayList<String>最初会创建一个大小为10(这是示例大小)的String[]数组,但是当您向ArrayList添加第11个元素时,它将创建一个新的大小为20的String [](同样,示例大小)并将旧数组的内容复制到新数组中。

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) 为了快速创建新数组,它使用以下方法: 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. 我个人将使用ArrayListLinkedList但是如果您坚持使用array那么您可以做的是在分配值之前检查大小为nxm的数组是否已满。 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. 如果已满,则创建一个新的多维数组,其大小为(n+1) x (m+1)并使用循环复制所有值。

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. 该方法不是可取的,因为它会使用更多的资源,因为您需要在阵列满时重新创建和复制该阵列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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