How to store a table in Java and retrieve data from it? [closed]
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this questionThe first column will have serial number, the second, third, and fourth will have x-coordinate, y-coordinate and velocity. I might have to retrieve any of the fields, given the serial number. Say I want to get the y-coordinate of serial number 7, or the velocity of serial number 10. One way is to have an inner class with x,y and velocity and map serial numbers to objects of the inner class. But it makes things look complicated and retrieving a particular field value seems complex. Any better solution?
Create a key object which implements hashCode() and equals() correctly. It appears that your serial numbers might be directly usable.
Create a data object with all fields you will need to store, and a getX() and setX() for each field x.
Create a Map<KeyObject,DataObject>
and use that with your (key, data) pairs.
Be very careful to remove outdated objects or you will have a memory leak.
What about using Arrays or Map (Collections -> Map ) ?
With arrays: just create one array with the dimensions you need. In your case:
Array[number_of_itens_to_store][3]
// 3 => 0 = id, 1 = x, 2 =y, 3 = speed
With Maps: take a look at http://download.oracle.com/javase/6/docs/api/java/util/Map.html . You can use your ID as the K
(key) and an array as the value.
You can take a look at Collections (http://download.oracle.com/javase/tutorial/collections/index.html) and even create your own collection, just following the tutorials.
精彩评论