Hashmap的简单使用及其部分要点
//map由于使用键值对来储存数据,经常用来储存和调用数据,尽量少遍历
public class 集合3要点 {
public static void main(String[] args) {
Map m = new HashMap();
m.put("0","0");
m.put("1","2");
m.put("2","4");
m.put("3","6");
m.put("4","null");//hashmap允许Null作为值
//map存储时,键不能重复,重复则会替换原来的值.发生覆盖
System.out.println(m.size());
String s = (String)m.get("1");
System.out.println(s);
m.remove("2");//移除键值对 但安全性较差
m.remove("1","2"); //移除键值对时 一般输入正确的键和正确的值来一起移除.
System.out.println(m.containsKey("3"));//查询集合中是否存在改键
System.out.println(m.containsValue("6"));//查询集合中是否存在该值
//遍历map应该将map集合中的键最为集合来遍历其中的数据
Set set = m.keySet(); //返回map集合中的键集合
Collections col = (Collections) m.values(); //返回map集合中的值集合
Iterator i = set.iterator();
while(i.hasNext()){
String key = (String)i.next();
String value = (String)m.get(key);
System.out.println(key+"="+value);
}
for(Object o : m.keySet()){
String key = (String)o;
String value = (String)m.get(key);
}
//HashMap要求重新存入的键值对当中键对象必须能使用HashCode和equeals重写