HashMap是android中一种小型存储类,但是同HashTable相比,它是不安全的,非同步的,因此在使用时通常要用关键字synchronized。
使用一个HashMap实例:
HashMap<String, String> sMap = new HashMap<String, String>();
sMap.put(K key, V value); //也就是将一个元素加入sMap存储器中
之后,若是我们想获取对应key的值value,可以使用如下的方法:
public V get(Object key);key就是上面我们存储时对应的key
通过ListView显示HashMap中存储的数据:
在main.xml中如下定义:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:id="@+id/listLinearLayout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal"> <ListView android:id="@id/android:list" android:layout_width="fill_parent" android:layout_height="wrap_content" android:drawSelectorOnTop="false" android:scrollbars="vertical"/> </LinearLayout> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10pt" android:orientation="vertical"> <TextView android:id="@+id/user_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10pt" /> <TextView android:id="@+id/user_ip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10pt" android:gravity="right" /> </LinearLayout>主代码(显示):
package com.android.HashMapUse; import java.util.ArrayList; import java.util.HashMap; import android.app.Activity; import android.app.ListActivity; import android.os.Bundle; import android.widget.SimpleAdapter; public class HashMapUse extends ListActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>(); HashMap<String,String> map1 = new HashMap<String,String>(); HashMap<String,String> map2 = new HashMap<String,String>(); HashMap<String,String> map3 = new HashMap<String,String>(); map1.put("user", "zhang"); map1.put("id", "192.168.1.00"); map2.put("user", "li"); map2.put("id", "192.168.1.01"); map3.put("user", "wang"); map3.put("id", "192.168.1.02"); list.add(map1); list.add(map2); list.add(map3); //这一步将HashMap中的数据(对应user,id)通过定义的子ListView显示 SimpleAdapter listAdapter = new SimpleAdapter(this, list, R.layout.childlist, new String[]{"user", "id"}, new int[]{R.id.user_name, R.id.user_ip}); setListAdapter(listAdapter); } }