Thứ Sáu, 28 tháng 6, 2013

Về HashMap trong java,android

Hôm nay nhìn thấy mấy đoạn code hơi lạ,chắc do chưa học java ,mày mò thử thì thấy họ áp dụng thế này:
 Ví dụ trong file arrays.xml mình có thế này :
   <?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="countries_names">
        <item>USA</item>
        <item>Russia</item>
    </string-array>

    <integer-array name="countries_codes">
        <item>1</item>
        <item>7</item>
    </integer-array>
</resources>

Vậy để mình có thế lấy được các giá trị trong  một cách linh hoạt thì dùng thế này :


String[] countriesNames = getResources().getStringArray(R.array.countries_names);
int[] countriesCodes = getResources().getIntArray(R.array.countries_codes);

HashMap<String, Integer> myMap = new HashMap<String, Integer>();
for (int i = 0; i < countriesNames.length; i++) {
    myMap.put(countriesNames[i], countriesCodes[i]);
}
Cách này thấy hay thật trong C++ ko biết có không ,giống như mình tạo một bản đồ tùy thích để lưu giá trị.

Để lấy giá trị từ hashmap ,dùng :
 HashMap<String, String> meMap=new HashMap<String, String>();
meMap.put("Color1","Red");
meMap.put("Color2","Blue");
meMap.put("Color3","Green");
meMap.put("Color4","White");
Iterator iterator = meMap.keySet().iterator();
while( iterator. hasNext() ){
    Toast.makeText(getBaseContext(), meMap.get(iterator.next().toString()), 
    Toast.LENGTH_SHORT).show();
}


Cái này thấy bên android khác java thì phải.Hoa xem cho ý kiến thêm .@_@

1 nhận xét:

  1. for (Integer i : user.keySet()) {
    Toast.makeText(getBaseContext(), i + " " +meMap.get(i).toString(),Toast.LENGTH_LONG).show();
    }

    Trả lờiXóa