What is the difference between using a Guava Table implementation and a 2D array if I know the size of the array beforehand?
Is one more efficient than the other? How? Would it make a difference in running time?
The most obvious and crucial difference is that an array is always indexed, with int
s, whereas a Table can be indexed with arbitrary objects.
Consider the Table Example from the Guava site:
Table<Vertex, Vertex, Double> weightedGraph = HashBasedTable.create();
weightedGraph.put(v1, v2, 4);
...
The indexing here happens via Vertex
objects. If you wanted to do the same with an array, you would have to add some getIndex
method to the Vertex
class, and accesss the array like this
double array[][] = new double[4][5];
array[v1.getIndex()][v2.getIndex()] = 4;
This is inconvenient and particularly hard to maintain - especially, when the indices may change (or when vertices have to be added/removed, although you mentioned that this is not the case for you).
Additionally, the Guava table allows obtaining rows or columns as separate entities. In a 2D array, you can always access either one row or one column of the array - depending on how you interpret the 2 dimensions of the array. The table allows accessing both, each in form of a Map
.
Concerning the performance: There will be cases where you'll have a noticable difference in performance. Particularly when you have a large 2D array of primitive types (int
, double
etc), and the alternative would be a large table with the corresponding reference types (Integer
, Double
etc). But again, this will only be noticable when the array/table is really large.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With