简体   繁体   中英

How to declare a generic type Multi-Dimensional array in java

我想在行中存储一个100个int元素的数组,即1行100个int数据类型。每个元素都包含一个100个对象的数组。如何在java或android中做到这一点。

Use a collection, a "List of List":

List<List<YourType>> matrix2D = new ArrayList<List<YourType>>();

This structure can easily store a table with 200 rows and 100 columns where each element is of type YourType .

Otherwise - if your size is fixed and you just want to store YourType values, theres no need for generics:

int rows = 200;
int columns = 200;
YourType[][] matrix2D = new YourType[rows][columns];

Here is how you can initialize and fill a two-dimensional Object array:

    Object value = 42;
    int rows = 100;
    int columns = 100;
    Object[][] myData = new Object[rows][columns];
    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < columns; c++) {
            myData[r][c] = value;
        }
    }

Note that the primitive int value 42 is autoboxed when it is stored in the Object[][]. If you don't want this you could use an int[][] instead.

If your type is int, it which be much more compact than using Integer type. (up to 6x smaller) To create a fixed size array you can

int[][] matrix = new int[200][100];
// set all values to 42.
for(int[] row : matrix) Arrays.fill(row, 42);

I think you need this.

100 T(Your Object) Objects in 200x100 matrix(array)

T[][][] t = new T[200][100][100] ; 

t[0][0][1] = new T();
t[0][0][2] = new T();
...
t[0][0][99] = new T();

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