In Google Guava (Java), how to bulk set values for

2020-04-20 06:08发布

问题:

I have a two dimensional array of data, e.g., V[][], that I want to bulk set on an ArrayTable instance.

Must I repeatedly call ArrayTable.put(R rowKey, C columnKey, V value)?

I cannot find a suitable constructor/static create helper or method, e.g., putAll(V[][] valueArr).

Please advise.

回答1:

There is not such a constructor.

Your best option is:

ArrayTable table = ArrayTable.create(
    ContiguousSet.create(Range.closedOpen(0, v.length), 
                       DiscreteDomain.integers()), 
    ContiguousSet.create(Range.closedOpen(0, v[0].length), 
                       DiscreteDomain.integers()));
for(int i = 0 ; i < v.length ; ++i) {
    for(int j = 0 ; j < v[i].length ; ++j) {
        table.set(i, j, v[i][j]);
    }
}


回答2:

There is no help in guava, as @JBNizet say, because the library can't know what you want to use as keys.

You can use 2 nested loops as @JBNizet say or you can create your own Table implementation that wraps your array and then call putAll method to copy your new table to the ArrayTable.

You don't need to implement every method on Table, you may throw UnsupportedOperationException on methods that otherwise should alter the content.



标签: java guava