gpt4 book ai didi

java - 在java中将ArrayList添加到另一个ArrayList

转载 作者:行者123 更新时间:2023-12-02 04:43:30 29 4
gpt4 key购买 nike

我想从每列的矩阵中找到最小值和最大值。我的功能

public static void findMinMax(double[][] matrix) {
ArrayList<Double> column = new ArrayList<Double>();
ArrayList<Double> minmax = new ArrayList<Double>();
ArrayList<ArrayList<Double>> minMaxValues = new ArrayList<ArrayList<Double>>();
for (int j=0;j<matrix[1].length;j++) {
column.clear();
minmax.clear();
for (int i=0;i<matrix.length;i++) {
column.add(matrix[i][j]);
}
double max = Collections.max(column);
double min = Collections.min(column);
minmax.add(min);
minmax.add(max);
try {
System.out.println("adding to final minmax " + j);
minMaxValues.add(minmax);
System.out.println(minMaxValues);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
System.out.println(minMaxValues);
}

问题在于,在最后一次迭代中,它仅将最后一个 minmax ArrayList 添加到 minMaxValues 中。这是输出的示例

adding to final minmax 0
[[-3.5, 4.5]]
adding to final minmax 1
[[-3.5, 4.5], [-3.5, 4.5]]
adding to final minmax 2
[[-3.5, 4.5], [-3.5, 4.5], [-3.5, 4.5]]
adding to final minmax 3
[[-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2]]
adding to final minmax 4
[[-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2]]
adding to final minmax 5
[[-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2]]
adding to final minmax 6
[[-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2], [-3.5, 4.2]]
adding to final minmax 7
[[-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2]]
adding to final minmax 8
[[-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2]]
adding to final minmax 9
[[-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2], [-3.9, 4.2]]
adding to final minmax 10
[[-3.9, 4.5], [-3.9, 4.5], [-3.9, 4.5], [-3.9, 4.5], [-3.9, 4.5], [-3.9, 4.5], [-3.9, 4.5], [-3.9, 4.5], [-3.9, 4.5], [-3.9, 4.5], [-3.9, 4.5]]

正如你所看到的,它在 minmax 10 之前工作正常,我不明白会发生什么。谁能帮我吗?

最佳答案

您需要重新初始化ArrayList<Double> minmax对于每次迭代。否则,您的结果列表将仅包含对同一列表的 11 个引用,其中包含您最后输入的值。

你需要移动

ArrayList<Double> minmax = new ArrayList<Double>();

在你的循环中。

关于java - 在java中将ArrayList添加到另一个ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29910499/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com