HashMap在Android开发中有哪些实际应用?

统计文本中各种单词出现的次数。

下面是简化的java代码


import java.util.HashMap;
import java.util.Map;

public class HashMapTest {
    
    
    public static void main(String[] args) {
    
    
        String text = "hello world hello my name is jack her name is anna";
        String[] words = text.split(" "); // 将文本按空格分隔成单词数组

        Map<String, Integer> wordCountMap = new HashMap<>();
        for (String word : words) {
    
    
            if (wordCountMap.containsKey(word)) {
    
     // 如果map中已经存在该单词,则增加计数
                int count = wordCountMap.get(word);
                wordCountMap.put(word, count + 1);
            } else {
    
     // 如果map中不存在该单词,则添加到map,并设置计数为1
                wordCountMap.put(word, 1);
            }
        }

        // 遍历输出每个单词出现的次数
        for (String key : wordCountMap.keySet()) {
    
    
            int count = wordCountMap.get(key);
            System.out.println(key + ": " + count);
        }
    }
}

网络请求

多信息上报

appId: 1234
channel: oppo/huawei
appVersion: 0.0.1
systemType: android/ios
userName: jack/null

上面的参数总数不固定,比如:没有上架前channel参数可以不传,未登录的情况下userName也可以不传。这个时候就可以用HashMap作为参数,发送给后端。

多条件查询

比如获取某个城市某个区某个地铁站附近500米以内的所有单间。

city:深圳市
district: 宝安区
subway_station: 宝安中心
distance: 500
house_type: 单间

这些条件,如果是可以增减的,条件总数量不确定。就可以用一个HashMap作为参数,传递给后端。

Retrofit库具体使用,可以参考这篇:Retrofit2系列:简单的Get请求
其中,@Body@QueryMap这两个入参注解,后面都可以跟HashMap。例如:

@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);

@POST
Call<User> getDataFromServer(@Url String url, @Body HashMap<String,Object> hashMap);

关于retrofit注解,可以参考:retrofit官方文档

EventBus

EventBus 中有多处用到HashMap,采用HashMap把event和订阅了这个event的对象集合存储起来,key是event对象的.class对象,value是CopyOnWriteArrayList。

关于EventBus的具体细节可以参考:EventBus实现组件通信的原理
源码如下:

public class EventBus {
    
    

    /** Log tag, apps may override it. */
    public static String TAG = "EventBus";
	...
	//下面的构造器中用到
	private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
    private static final Map<Class<?>, List<Class<?>>> eventTypesCache = new HashMap<>();
    //这个是核心HashMap在下面的构造器里面赋值
    private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
    ...

    public static EventBusBuilder builder() {
    
    
        return new EventBusBuilder();
    }
    
    public EventBus() {
    
    
        this(DEFAULT_BUILDER);
    }

    EventBus(EventBusBuilder builder) {
    
    
		...
		//在这里new 了个HashMap对象
        subscriptionsByEventType = new HashMap<>();
        typesBySubscriber = new HashMap<>();
		...
    }

}

缓存

一般缓存使用LinkedHashMap,LinkedHashMap继承自HashMap,所以也可以说缓存用的也是HashMap。

public class LinkedHashMap<K,V>
    extends HashMap<K,V>
    implements Map<K,V>
{
    
    

	......
}

Glide图片缓存。缓存比较复杂,后面有时间再讲。

猜你喜欢

转载自blog.csdn.net/zhangjin1120/article/details/131270677