备战蓝桥杯java(十):算法竞赛中的常用API :HashMap 和 TreeMap
程序员文章站
2022-06-25 18:47:54
...
摘要
本文主要介绍Map接口下的HashMap和TreeMap。
HashMap
HashMap是基于哈希表的 Map 接口的实现,是无序的
-
clear()
//清空。 -
containsKey(Object key)
//如果包含指定键,返回true -
containsValue(Object value)
//如果包含指定值, 返回true -
get(Object key)
//返回指定键所映射的值;如果对于该键来说,此映射不包含任何映射关系,则返回 null。 -
isEmpty()
//如果此映射不包含键-值映射关系,则返回 true -
put(K key, V value)
//在此映射中关联指定值与指定键。 -
remove(Object key)
//从此映射中移除指定键的映射关系(如果存在)。 -
size()
返回此映射中的键-值映射关系数。
实例
Map<Integer, Integer> m = new HashMap<>();//定义格式
m.put(100,1);
System.out.print(m.get(100)); // 1
TreeMap
TreeMap是基于红黑树实现的,是有序的, 可进行排序。
此实现为 containsKey、get、put 和 remove 操作提供受保证的 log(n) 时间开销
-
clear()
//清空 -
containsKey(Object key)
//如果包含指定键,返回true -
containsValue(Object value)
//如果包含指定值, 返回true -
get(Object key)
//返回指定键的值, 如果不存在返回null -
firstKey()
//返回此映射中当前第一个(最低)键。 -
lastKey()
返回映射中当前最后一个(最高)键 -
ceilingKey(K key)
返回大于等于给定键的最小键;如果不存在这样的键,则返回 null。 -
floorKey(K key)
返回小于等于给定键的最大键;如果不存在这样的键,则返回 null。
遍历,HashMap和TreeMap可以根据迭代器遍历,但,它俩不能直接遍历,但先将键或者值,或者键值对 转化为set,然后通过set的迭代器遍历。
- 通过keySet()获得键,然后根据键遍历值
Map<Integer, String> m = new HashMap<>();
m.put(1,"A");
m.put(2,"B");
Set<Integer> s = m.keySet();
Iterator it = s.iterator();
while(it.hasNext()){
int key = it.next();
int value = m.get(key);
System.out.print(value);
}
- 直接通过values()遍历值
Collection c = map.values();
Iterator it= c.iterator();
while(it.hasNext()){
int value = it.next();
System.out.print(value);
}
- 使用entrySet() + Map.Enter() 直接获取键和值。
Map<Integer, Integer> m = new TreeMap<>();
m.put(1, 100);
m.put(2, 200);
Iterator it = m.entrySet().iterator();
while(it.hasNext()){
Map.Entry<Integer, Integer> ent = (Entry<Integer, Integer>) it.next();
int key = ent.getKey();
int value = ent.getValue();
System.out.print(key+":"+value+"\n");
输出:
1:100
2:200
上一篇: Python编程基础记一次课堂笔记:for循环&函数编写
下一篇: mfcdll控件中遇到的问题