Possible Duplicate:
Table like java data structure
Does anyone know if there's a good general-purpose Table-based structure that I can use for manipulating data? ResultSet is an interface, so am I stuck having to fully implem开发者_JAVA技巧ent something if I want similar functionality without a database? Apache Commons Collections does not seem to have anything immediately suitable.
Usually you use a List
or Set
of Javabeans for this. Each Javabean in turn represents one real world entity, like a row in a database. For example an User
:
public class User {
private Long id;
private String name;
private Integer age;
// Add/generate getters+setters.
}
with
List<User> users = new ArrayList<User>();
users.add(new User(1L, "foo", 30));
users.add(new User(2L, "bar", 20));
//...
The List
provides methods for fast access by index.
For an undetermined amount of properties (columns) you may consider to use a Map<String, Object>
instead where the key represents the property (column) name.
List<Map<String, Object>> table = new ArrayList<Map<String, Object>>();
Map<String, Object> row = new HashMap<String, Object>();
row.put("id", 1L);
row.put("name", "foo");
row.put("age", 30);
table.add(row);
// ...
It only adds a bit more overhead than a simple Javabean since those string keys needs to be stored in the heap as well.
If you don't care about column names, then you can also just go ahead with a List<List<Object>>
or maybe even a less flexible Object[][]
. With both you can easily access elements by x
and y
.
Why not use an In-Memory Database, such as HSQLDB or H2. They are very lightweight and fast, provide the JDBC interface you seem to want and also provide the JOIN functionality you mention.
Google Guava libraries offer several general purpose Table implementations - HashBasedTable, TreeBasedTable. The classes are generic so any class can act as a row/column key.
Example from the docs:
Table<Vertex, Vertex, Double> weightedGraph = HashBasedTable.create();
weightedGraph.put(v1, v2, 4.0);
weightedGraph.put(v1, v3, 20.0);
weightedGraph.put(v2, v3, 5.0);
weightedGraph.row(v1); // returns a Map mapping v2 to 4, v3 to 20
weightedGraph.column(v3); // returns a Map mapping v1 to 20, v2 to 5
Java 6 has a CachedRowSet
interface and comes with a Sun class, CachedRowSetImpl
. This probably is the closest thing stock out of the box to what you're looking for. It's designed to be populated by a ResultSet
.
If that suits you it's probably exactly what you're looking for.
If not, you may have issues populating it properly.
Maybe something like the DefaultTableModel
will meet your requirements. It is generally used with a JTable to display data but it can be used stand alone.
Or the BeanTableModel
based on the RowTableModel
has a few more dynamic features that allows you to access rows of data easier.
精彩评论