I want to create a Hashtable in Java program. The Hashtable must have multiple fields (for now i want to store 3 columns which i read from DB). How can I store multiple columns as Hashtable stor开发者_Go百科es key value pairs. I would like to keep the first column as key and the 3rd column as value. Please help!! Thanks!
First, you need a new class which can store the values:
public class Values {
public final String foo;
public final Long bar;
public final Long foobar;
public Values(final String foo, final Long bar, final Long foobar) {
this.foo = foo;
this.bar = bar;
this.foobar = foobar;
}
}
Than you can create your Hashtable
(do you really need thread safety?) like this:
final Map<String, Values> container = new Hashtable<String, Values>();
If you don't need thread safety, you can use HashMap
instead.
You can just make your value an object that contains the 3 values you want to store associated with the key.
The value in the hashtable (concurrenthashmap is a better alternative in most of the scenarios) can be be any object (even your db entity; so you are free to wrap the values of hashtable as any object you desire).
what do you mean by : "The Hashtable must have multiple fields (for now i want to store 3 columns which i read from DB)."
HashTable can have key-value pairs and keys should be unique, So any column in your table which is Unique and not null, for example primary-key can be used as key in the hashtable, the corresponding values can be anything you want to store, it can either be only the values in 3rd column or you can make a composite object of rest all fields and put that object as value against the primary-key.
And if you do not have thread-safety issue, go for HashMap for better performance.
You can create a HashTable where the first column would be for the Key and the second column will contain a Vector or an array or a class or whatever. That's how you will create a hashtable with different columns
精彩评论