简体   繁体   English

如何在Java中声明泛型类型多维数组

[英]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 . 这种结构可以轻松地存储具有200行和100列的表,其中每个元素都是YourType类型。

Otherwise - if your size is fixed and you just want to store YourType values, theres no need for generics: 否则-如果您的大小是固定的,并且只想存储YourType值,则不需要泛型:

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数组的方法:

    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[][]. 注意,原始int值42存储在Object [] []中时会自动装箱。 If you don't want this you could use an int[][] instead. 如果您不希望这样做,可以使用int [] []代替。

If your type is int, it which be much more compact than using Integer type. 如果您的类型是int,则它比使用Integer类型紧凑得多。 (up to 6x smaller) To create a fixed size array you can (小6倍)要创建固定大小的数组,您可以

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) 200x100矩阵中的100个T(您的对象)对象(数组)

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

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

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