Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guava Table vs. 2D array

Tags:

java

arrays

guava

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?

like image 567
Bernice Avatar asked Dec 20 '22 15:12

Bernice


1 Answers

The most obvious and crucial difference is that an array is always indexed, with ints, 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.

like image 95
Marco13 Avatar answered Jan 27 '23 15:01

Marco13