[英]Java: Turning a Matrix into a List: my add method is not working and I don't know why
I keep on get an error that says my add method says no suitable method found. 我不断收到一个错误,提示我的添加方法未找到合适的方法。 The goal of the program is to get all the values of a matrix into a list and I can not get it to work because it keeps on giving me an error at this line: 该程序的目标是将矩阵的所有值都放入列表中,但我无法使其正常工作,因为它不断在此行给我一个错误:
list.add(mat[i][j]);
The entire code looks like this: 整个代码如下所示:
List<Integer> go(int[][] mat)
{
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < mat.length; i++)
{
for (int j = 0; j < mat[i].length; j++)
{
list.add(mat[i][j]);
}
}
return list;
}
Your function returns a List<Integer>
, but your list
object is declared as an ArrayList<String>
, which you are trying to add mat[i][j]
to. 您的函数返回List<Integer>
,但是您的list
对象被声明为ArrayList<String>
,您正在尝试向其添加mat[i][j]
。 Furthermore, mat[i][j]
is itself an int
, so list
should be an ArrayList<Integer>
. 此外, mat[i][j]
本身是一个int
,因此list
应该是ArrayList<Integer>
。
List<Integer> go(int[][] mat)
{
int capacity = mat.length * mat[0].length; // Not needed.
List<Integer> list = new ArrayList<>(capacity);
for (int i = 0; i < mat.length; i++)
{
for (int j = 0; j < mat[i].length; j++)
{
list.add(mat[i][j]);
}
}
return list;
}
String instead of Integer. 字符串而不是整数。 And better style is to let the variable already be a List. 更好的样式是让变量已经是List。
Immediately reserving the right amount of list entries is an optimization: no resizing during adding of values, and not reserving too many room. 立即保留适当数量的列表条目是一种优化:在添加值期间不调整大小,并且不保留太多空间。
In fact a linear array might also be an option. 实际上,线性阵列也可能是一种选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.