How want to create a Map<String , Object>
.
In this map everytime the Object is a string. But Now I want to put a class in the object in addition to that. Is this a good way to mix string and a class object? If yes, when I iterate through the map, how can I distiguish between class and string?
Java HashMap is a hash table based implementation of Java's Map interface. A Map, as you might know, is a collection of key-value pairs. It maps keys to values. Following are few key points to note about HashMaps in Java - A HashMap cannot contain duplicate keys.
As with any other object, you can create String objects by using the new keyword and a constructor. The String class has 11 constructors that allow you to provide the initial value of the string using different sources, such as an array of characters.
The classic Java way is to pass the value Map as an argument to the constructor of Person and let person read the properties from the map. This way you can have multiple ways for constructing a Person object. Either by passing arguments directly, or passing the map.
8 Answers. Show activity on this post. Then you can create a Map<String,ComputeString> object like you want in the first place. Using a map will be much faster than reflection and will also give more type-safety, so I would advise the above.
Map<String, Object> map = new HashMap<String, Object>();
...
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getValue() instanceof String) {
// Do something with entry.getKey() and entry.getValue()
} else if (entry.getValue() instanceof Class) {
// Do something else with entry.getKey() and entry.getValue()
} else {
throw new IllegalStateException("Expecting either String or Class as entry value");
}
}
Every objects (excluding interfaces) in java extends Object
, so your approach is correct.
To know whether an object is a string or other object type, use the instanceof
keyword.
Example:
Map<String, Object> objectMap = ....;
for (String key : objectMap.keySet()) {
Object value = objectMap.get(key);
if (value instanceof String) {
System.out.println((String) value);
} else if (value instanceof Class) {
System.out.println("Class: " + ((Class)value).getName());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With