Ari M
Ari M

Reputation: 1426

What data structure can I use for a table in Java?

I need to store data that comes as a table, what can I use in Java to do it?

The keys that form the columns and rows are Object, so I need a structure that can be represented as a triplet: <Object Row,Object Col, Object Val> where for each Row,Col there is only one val, and that for all Row X Col, there is a value.

Or should I use a simple bi-dimensional array and translate the indexes to their corresponding Object?

Upvotes: 1

Views: 3335

Answers (3)

JB Nizet
JB Nizet

Reputation: 691685

If Guava is not an option, I would use a Map<Coordinate, Val>, where Coordinate is a custom object containing your row and column objects, and implementing equals and hashCode properly.

Upvotes: 3

dogbane
dogbane

Reputation: 274542

Guava provides a Table collection which might be what you need. See the Guava User Guide for more information.

Example usage:

Table<Integer, Integer, Object> myTable = HashBasedTable.create();
myTable.put(1, 2, "foo"); // put an object in row 1, column 2.

If you don't want to use Guava, just use a two-dimensional array, as shown below:

Object[][] myTable2 = new Object[5][5];
myTable2[0][1] = "foo";

Upvotes: 8

NimChimpsky
NimChimpsky

Reputation: 47280

HashMap<Object, ArrayList> myTable = new HashMap<Object, ArrayList>();

Upvotes: 1

Related Questions