2013-04-08 14 views
6

Ho un metodo in una classe, che inizializza una HashMap e inserisce alcune chiavi e valori al suo interno, quindi il metodo restituisce la HashMap. Come posso recuperare la HashMap restituita?Metodo di restituzione HashMap

public Map<String, String> getSensorValue(String sensorName) { 

registerSensor(sensorName); 
sensorValues.put("x","25"); 
sensorValues.put("y","26"); 
sensorValues.put("z","27"); 
return sensorValues; 
} 

E qui io chiamo questo metodo da un'altra classe:

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

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

Ma non funziona in questo modo

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

rende il mio crash dell'applicazione Android. Il punto è di ritornare in qualche modo restituito HashMap.

+0

Avete controllato il vostro logcat? – Zyerah

+1

pubblica la tua eccezione (puoi trovarla nel tuo output logcat in eclissi) – Dodge

risposta

12

Non è necessario copiare la mappa. Basta provare a utilizzare il riferimento restituito:

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

Il tuo metodo deve restituire una Map<String,String>. Nel codice che hai postato, i valori di sensore Map non vengono mai inizializzati.

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; 
} 
0

HashMap sensValues ​​= new HashMap(); Imposta 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); 
      } 
4

Quasi come ha dichiarato Rich nella sua risposta, ma il metodo restituisce un Map che non può essere gettato in una HashMap. Prova questo

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

Oppure, in alternativa modificare il metodo di getSensorValue in modo che restituisca un HashMap

0

Inoltre è possibile provare passa da aproach di riferimento,

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"); 

    }