Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 757
Saurabh Kumar Avatar asked Jul 29 '11 09:07

Saurabh Kumar


People also ask

What is Map String object in Java?

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.

Can we create an object of String class?

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.

Can we create object of Map in Java?

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.

Can we Map a String?

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.


2 Answers

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");
    }
}
like image 65
Bohemian Avatar answered Sep 30 '22 19:09

Bohemian


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());
    }
}
like image 21
Buhake Sindi Avatar answered Sep 30 '22 18:09

Buhake Sindi