Hashmap的使用

HashMap是android中一种小型存储类,但是同HashTable相比,它是不安全的,非同步的,因此在使用时通常要用关键字synchronized

使用一个HashMap实例:

HashMap<String,String>sMap=newHashMap<String,String>();

sMap.put(Kkey,Vvalue);//也就是将一个元素加入sMap存储器中

之后,若是我们想获取对应key的值value,可以使用如下的方法:

publicVget(Objectkey);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>
Childlist.xml:

<?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); } }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值