简体   繁体   中英

How to use hashmap with multiple data types for request params?

Is it possible to use putBoolean with put ? I can't figure out how to have a hashmap that can handle string and boolean request params at the same time.

Map<String,String> params = new HashMap<String, String>();

params.put("name", "Name here");
params.put("gender", "Female");
params.putBoolean("isStudent", true); //this is not working...

Thanks for your help.

You can can store a object format like this

Map<String,Object> params = new HashMap<String, Object>();

params.put("name", "Name here");
params.put("gender", "Female");
params.put("isStudent", true);

While getting data you can typecast object into literals. Like

// In case of String 
String name=(String)param.get("name");
// In case of Boolean 
Boolean isStudent=(Boolean)param.get("isStudent");

There is no putBoolean() method in HashMap. Try this

Map<String,Object> params = new HashMap<String, Object>();

params.put("name", "Name here");
params.put("gender", "Female");
params.put("isStudent", true);

when you get that key use this code.

Boolean isStudent = (Boolean)params.get("isStudent");
    Map<String, Object> params = new HashMap<String, Object>();

    params.put("name", "Name here");
    params.put("gender", "Female");
    params.put("isStudent", true);

    for (String s : params.keySet()) {
        Object obj = params.get(s);
        if (obj instanceof Boolean) {
            //do something
        }
        else if (obj instanceof String) {
            //do something
        }
    }

You can use the type "Object", but only if you really need it. When you use Object type, you can put any value to your map, and it may occur errors.

Make your map value as Object

Map<String,Object> params = new HashMap<String, Object>();

params.put("name", "Name here");
params.put("gender", "Female");
params.putBoolean("isStudent", true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM