简体   繁体   中英

How could I add and update data in random order in a two-dimension matrix in Java

for example the input is: (row, column, weight), such as (0,2,10.0),(1,2,3.0), (2,1,11.3), (1,2, 15.0)

the result should be:

0 1 2

0. . 10.0

1. . 15.0

2. 11.3.

(the data would be both inserted and updated )

I have noticed that it could not be done by simply using add(index i, elements e) or set() method provided by Arraylist in Java. Because it would throw :IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size()) for instance, when I try to insert (0,2,5.0) after inserting (0,0,3.0).

The simplest thing to do with an ArrayList is to add null elements as needed to increase the size before trying to set an element at a given index.

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

This is likely to perform quite poorly on large matrices, because of all the object creation performed here, and the poor locality of reference.

If possible, a contiguous array of primitive double elements will be better for large, dense data sets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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