ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Map과 HashMap 클래스
    예전 글들/Android 2011. 5. 10. 12:45
    반응형
    우선 영어로 된 설명을 복사해서 보면

    A Map is a data structure consisting of a set of keys and values in which each key is mapped to a single value. The class of the objects used as keys is declared when the Map is declared, as is the class of the corresponding values. (이 긴 문장을 간단히 해석하면 "Map은 키와 값들로 이루어졌고 각각의 키는 하나의 값과 쌍을 이룬다." 뭐 그런거 같군)

    A Map provides helper methods to iterate through all of the keys contained in it, as well as various methods to access and update the key/value pairs. (다양한 함수에서 키/값 쌍들로 접근하고 업데이트 할 수 있다는군 이것들도 쌍으로 노네~~ -_-+)

    안드로이드에서 사용 예제를 보면(공부하던 부분은 안드로이드 하드웨어 부분 중 베터리 관련입니다.)

    얘네들 추가해주고
    import java.util.HashMap;
    import java.util.Map;

    사용하려는 함수 안에 다음과 같이 사용하면 됩니다.
    private static final Map<Integer, String> healthValueMap = new HashMap<Integer, String>() {
      {
       put(BatteryManager.BATTERY_HEALTH_DEAD, "Dead");
       put(BatteryManager.BATTERY_HEALTH_GOOD, "Good");
       put(BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE, "Over Voltage");
       put(BatteryManager.BATTERY_HEALTH_OVERHEAT, "Over heating");
       put(BatteryManager.BATTERY_HEALTH_UNKNOWN, "Unknown");
       put(BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE, "Failure, but unknown");
       put(-1, "Not Reported");
      }
     };

    그리고 사용법은

    우선
    int batteryHealth = intent.getIntExtra("health", -1); 이런식으로 키값을 받아오는 듯하고

    여기서 getIntExtra() 함수에 대한 설명을 추가하면

    - int android.content.Intent.getIntExtra(String name, int defaultValue)
    - public int getIntExtra (String name, int defaultValue)
    Since: API Level 1
    Retrieve extended data from the intent. (intent에서 왔고)

    Parameters
    name: The name of the desired item. [요구되는(사용되려는(?)) 아이템의 이름]
    defaultValue:  the value to be returned if no value of the desired type is stored with the given name. [만약 요구되는 저장되어 있는 주워진 이름의 요구되는 타입의 값이 없다면 돌려주는 값, 쉽게 말해 찾으려는 값이 없으면 요걸 돌려준다는거죠.]

    Returns
    the value of an item that previously added with putExtra() or the default value if none was found.

    다시 소스로 돌아와서
    String batteryInfo = "Battery Info:\nHealth=" + healthValueMap.get(batteryHealth) + "\n" + "Status=" + statusValueMap.get(batteryStatus) + "\n" + "Charged % = " + chargedPct + "%\n" + "Plugged = " + pluggedValueMap.get(batteryPlugged) + "\n" + "Type = " + batteryTech + "\n" + "Voltage = " + batteryVoltage + " volts\n" + "Temperature = " + batteryTemp + "좧\n" + "Battery present = " + battery + "\n";

    위에 진한색 칠한 것처럼 batteryHealth로 받은 int값을 받아서 Map에 있는 키값과 비교하여 그에 맞는 값을 돌려주는 듯하는군요.
    잘만 사용하면 쓸 때는 많겠죠? 어디다 쓰지??

    [ 소스 출처: 시작하세요. 안드로이드 프로그래밍(위키북스) ]

    반응형

    댓글

Designed by Tistory.