An ArrayList
is not an array
定义一个包含ArrayList
个对象的ArrayList
.但是你试图放入一个int
个原始值的array.数组是not和ArrayList
.所以你收到一个错误,解释你违反了类型系统.你不能把香蕉放在养cat 的地方.
Define a list of arrays: List < int[] >
相反,将您的ArrayList
定义为包含一个数组:
ArrayList < int[] > list = new ArrayList < int[] > ( );
请注意,您不需要重复等号右侧的参数化类型.在现代Java中,编译器可以通过查看equals的左侧来推断类型.
ArrayList < int[] > list = new ArrayList <> ( );
此外,通常最好使用提供所需功能的最高超类或超接口.所以你可以把你的ArrayList
称为List
.在Java 21+中,你可以使用SequencedCollection
(JEP 431).
List < int[] > list = new ArrayList < int[] > ( );
完整示例代码:
// Prepare.
List < int[] > list = new ArrayList <> ( );
int rows = 3, cols = 3, counter = 1;
int[][] mat = new int[ rows ][ cols ];
// Populate array.
for ( int i = 0 ; i < rows ; i ++ )
{
for ( int j = 0 ; j < cols ; j ++ )
{
mat[ i ][ j ] = counter ++ ;
}
}
// Populate ArrayList.
for ( int index = 0 ; index < rows ; index ++ )
{
list.add ( mat[ index ] );
}
// Report.
list.forEach ( ints -> System.out.println ( Arrays.toString ( ints ) ) );
运行时:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]