Is there a way to store multiple data types in a single hash table variable?

I have a Hashtable that has a String key and a value like String , but I have reached a point in my project where I need to be able to store several different data types. For example, I will need to store int , String , Date , etc. All In One Hashtable .

+6
source share
5 answers

HashTable or any Map collection can handle this, with the exception of int and other primitive types: you cannot store primitive types, only Object references. int must be wrapped as an Integer object.

+7
source
 Map<String, Object> map = new HashMap<String, Object>() 

This gives you a map with keys of type String and values โ€‹โ€‹of type Object, which basically means any descendant of type Object (Date, Integer, String, etc.). Other answers correctly indicate that instead of using primitives such as int, boolean, you need to use their analogues Integer, Boolean, etc.

The return type of the get operation on such a map is Object . Therefore, the developer must properly handle type information.

A good answer to the question of what is the difference between a Hashtable and a HashMap is provided here .

+6
source

You can save its generic Object data type, although this will not allow primitive data types.

+4
source

While this is possible, it is not a good idea at all. Most often, this leads to exceptions and type casting problems.

HashTable can be configured to save common objects, unlike certain types of classes, however, the conversion of types when they are removed does not occur automatically.

To return an object from a collection, some form of type checking procedure needs to be developed.

You better create a separate collection for each type of class that you want to keep.

PS: I would also recommend using a HashMap instead of a HashTable. HashTable is deprecated.

+4
source

Change your HashTable to Hashtable<String, Object> , and if you want to save the int , you need to first transfer it (or use autocast) to Integer . Having received your value from the table, you can determine your type if(value instanceof String) , etc. For any type.

0
source

Source: https://habr.com/ru/post/920914/


All Articles