随笔(Map接口)
map接口:map<k,v>
k: key钥匙 其中的键。
v:value值 锁里面存的东西。
也叫哈希表、散列表:常用于存键值对结构的数据。其中的键不能重复,值可以重复(建重复会覆盖以前的值)。
特点:1、可以根据键来提取对应的值。 2、键不允许重复,如果重复值会被覆盖。
3、存放的都是无序数据。4、初始容量是16.默认的加载因子是0.75。
Map接口:hashmap实现类、treemap实现类。
HashMap实现类
常用方法HashMap的三种遍历方式
String key = null;
String value = null;
// 获取键值对的迭代器
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
key = (String) entry.getKey();
value = (String) entry.getValue();
System.out.println("key:" + key + "---" + "value:" + value);} String key = null;
String value = null;
// 获取键集合的迭代器
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
key = (String) it.next();
value = (String) map.get(key);
System.out.println("key:" + key + "---" + "value:" + value);
} String value = null;
// 获取值集合的迭代器
Iterator it = map.values().iterator();
while (it.hasNext()) {
value = (String) it.next();
System.out.println("value:" + value);
}
}
}字符串中的字母统计
public class Test007 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = new Scanner(System.in).nextLine();
HashMap<Character, Integer> hashmap = new HashMap<Character, Integer>();
for(int i = 0 ;i<str.length();i++) {
char c = str.charAt(i);
Integer count = hashmap.get(c);
if(count==null) {
hashmap.put(c, 1);
}else {
hashmap.put(c, count+1);
}
}
System.out.println(hashmap);
}
}
查看11道真题和解析