HashMap Return Method

I have a method in a class that initializes a HashMap and puts some keys and values ​​into it, then the method returns a HashMap. How to get 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 doesn’t work that way

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

Makes Android app crash. The point is to somehow bring back the HashMap.

+6
source share
5 answers

You do not need to copy the card. Just try using the return link:

 Map<String, String> map = sensVal.getSensorValue("..."); 
+12
source

Your method should return Map<String,String> . In the code you posted, 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; } 
+5
source

Almost like Rich said in his answer, but your method returns a Map that cannot be attributed to a HashMap . try it

 Map<String, String> map = sensVal.getSensorValue("..."); 

Or, alternatively, change the getSensorValue method so that it returns a HashMap

+4
source

HashMap sensValues ​​= new HashMap (); Set mapSet = (Set) sensValues.entrySet ();

Iterator mapIterator = mapSet.iterator ();

  while (mapIterator.hasNext()) { Map.Entry mapEntry = (Map.Entry) mapIterator.next(); String keyValue = (String) mapEntry.getKey(); String value = (String) mapEntry.getValue(); System.out.println("Key : " + keyValue + "= Value : " + value); } 
0
source

You can also try following the aproach link,

  void main(){ public static HashMap<String, String> sensValues = new HashMap<String, String>(); AllSensors sensVal = new AllSensors(); sensVal.setSensorValue(sensValues ,"orientation"); String something = sensValues.get("x"); } public void setSensorValue(Map<String, String> sensorValues, String sensorName) { registerSensor(sensorName); sensorValues.put("x","25"); sensorValues.put("y","26"); sensorValues.put("z","27"); } 
0
source

All Articles