Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap return method

I have a method in a class, which initialize a HashMap and put some keys and values inside it, then the method returns the HashMap. How can I retrieve the returned HashMap?

public Map<String, String> getSensorValue(String sensorName) {
    registerSensor(sensorName);
    sensorValues.put("x","25");
    sensorValues.put("y","26");
    sensorValues.put("z","27");
    return sensorValues;
}

And here I call this method from another class:

public static HashMap<String, String> sensValues = new HashMap<String, String>();

AllSensors sensVal = new AllSensors();
sensValues.putAll(sensVal.getSensorValue("orientation"));
String something = sensValues.get("x");

But it does not work in this way

sensValues.putAll(sensVal.getSensorValue("orientation"));

Makes my android application crash. The point is to retrive returned HashMap somehow.

like image 530
secret Avatar asked Apr 08 '13 08:04

secret


People also ask

How do I return a HashMap method?

HashMap get() Method in Java get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.

What is the return type of HashMap?

Returns true if this map contains a mapping for the specified key. Returns true if this map maps one or more keys to the specified value.

Does a HashMap get return a reference?

It returns a reference.

What is the return type of put K V method in HashMap?

put(key,value) is return type of 'value' in hashmap. put(key,value) where hashmap is defined as follows :- HashMap<Integer,String> hashmap = new HashMap<Integer,String>(); so return type of hashmap. put(key,value) is String,always .


2 Answers

You shouldn't have to copy the map. Just try using the returned reference:

Map<String, String> map = sensVal.getSensorValue("...");
like image 160
rich Avatar answered Nov 12 '22 08:11

rich


Your method needs to return a Map<String,String>. In the code you have posted, the Map sensorValues is never initialized.

public Map<String, String> getSensorValue(String sensorName) {
    Map<String,String> sensorValues = new HashMap<String,String>();
    registerSensor(sensorName);
    sensorValues.put("x","25");
    sensorValues.put("y","26");
    sensorValues.put("z","27");
    return sensorValues;
}
like image 37
Kevin Bowersox Avatar answered Nov 12 '22 07:11

Kevin Bowersox