开发者

want to create a map<String , Object> ,Object can be String and can be class Object

How want to create a Map<String , Object>.

In this map everytime the Object is a string. B开发者_运维问答ut 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?


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());
    }
}


As you have Object as a value in Map you can add any object as value as String, Integer, Your custom class...

And to distiguish between class and string while iterating you can use instance of to check whether it is String or not.

ie:

Set<String> mapKeys = myMap.keySet();
for (String key :  mapKeys) {
    Object value = myMap.get(key);
    if (value instanceof String) {
        //value is of type String
    } else if (value instanceof MyClass) {
        //value is of type MyClass
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜