我如何在Java的二维矩阵中以随机顺序添加和更新数据

问题描述 投票:-2回答:1

例如,输入为:(行,列,权重),例如(0,2,10.0),(1,2,3.0),(2,1,11.3),(1,2,15.0)] >

结果应该是:

0 1 2

0。 。 10.0

1。 。 15.0

2。 11.3。

(数据将同时为已插入

已更新

我注意到,仅使用Java中Arraylist

提供的add(index i,elements e)set()方法无法完成此操作。例如,因为当我尝试在插入(0, 0,3.0)。例如输入是:(行,列,权重),例如(0,2,10.0),(1,2,3.0),(2,1,11.3),(1,2,15.0)结果应为:0 1 2 0。 。 10.0 1。 。 15.0 2。 11.3。 (数据...
java matrix arraylist add
1个回答
0
投票
ArrayList最简单的操作是根据需要添加null元素以增加大小,然后再尝试将元素设置为给定索引。

private final List<List<Double>> matrix = new ArrayList<>(); public OptionalDouble set(int i, int j, double value) { while (i >= matrix.size()) matrix.add(new ArrayList<>()); List<Double> row = matrix.get(i); while (j >= row.size()) row.add(null); Double old = row.set(j, value); return (old == null) ? OptionalDouble.empty() : OptionaDouble.of(old); } public OptionalDouble get(int i, int j) { List<Double> row = (i < matrix.size()) ? matrix.get(i) : Collections.emptyList(); Double value = (j < row.size()) ? row.get(j) : null; return (value == null) ? OptionalDouble.empty() : OptionalDouble.of(value); }

© www.soinside.com 2019 - 2024. All rights reserved.