一、HashMap的添加方法:
1.put()方法,每次可以向HashMap中添加一个键值对。(添加的数据无序,顺序和哈希算法有关)。
package lesson01_eclipseSet;
import java.util.HashMap;
public class likou {
public static void main(String[] args) {
HashMap<String,String> hashmap1 = new HashMap<String,String>();
hashmap1.put("1", "malong");
hashmap1.put("2", "xuxin");
hashmap1.put("3", "zhangjike");
System.out.println(hashmap1);
}
}
输出结果:
2.putAll()方法,可以将一个HashMap对象整体添加到另一个HashMap对象中。(如果有重复的元素,会被覆盖为新的值)。
package lesson01_eclipseSet;
import java.util.HashMap;
public class likou {
public static void main(String[] args) {
HashMap<String,String> hashmap1 = new HashMap<String,String>();
hashmap1.put("1", "malong");
hashmap1.put("2", "xuxin");
hashmap1.put("3", "zhangjike");
HashMap<String,String> hashmap2 = new HashMap<String,String>();
hashmap2.put("1", "lingaoyuan");
hashmap2.put("4", "wangchuqin");
hashmap2.put("5", "fanzhendong");
hashmap1.putAll(hashmap2);
System.out.println(hashmap1);
}
}
?输出结果:
二、HashMap的删除方法
1.remove()方法:可以单次删除一个元素(如果删除的元素不存在,不会报错)
package lesson01_eclipseSet;
import java.util.HashMap;
public class likou {
public static void main(String[] args) {
HashMap<String,String> hashmap1 = new HashMap<String,String>();
hashmap1.put("1", "malong");
hashmap1.put("2", "xuxin");
hashmap1.put("3", "zhangjike");
System.out.println(hashmap1);
System.out.println("=========");
hashmap1.remove("1");
//value值不存在
hashmap1.remove("2", "zhangsan");
System.out.println(hashmap1);
}
}
?输出结果:
三、查询方法
get()方法:传入key值,即可查询到value值
package lesson01_eclipseSet;
import java.util.HashMap;
public class likou {
public static void main(String[] args) {
HashMap<String,String> hashmap1 = new HashMap<String,String>();
hashmap1.put("1", "malong");
hashmap1.put("2", "xuxin");
hashmap1.put("3", "zhangjike");
Object value = hashmap1.get("1");
System.out.println(value);
}
}
输出结果:
四、 遍历方法
1.EntrySet()方法:可以得到一个Entry对象的结果集
package lesson01_eclipseSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class likou {
public static void main(String[] args) {
HashMap<String,String> hashmap1 = new HashMap<String,String>();
hashmap1.put("1", "malong");
hashmap1.put("2", "xuxin");
hashmap1.put("3", "zhangjike");
for (Entry<String, String> keys : hashmap1.entrySet()) {
System.out.println(keys);
}
}
}
输出结果:
2.KeySet()方法:先使用keySet函数,获取到HashMap的所有的key的集合对象。?
package lesson01_eclipseSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class likou {
public static void main(String[] args) {
HashMap<String,String> hashmap1 = new HashMap<String,String>();
hashmap1.put("1", "malong");
hashmap1.put("2", "xuxin");
hashmap1.put("3", "zhangjike");
Set<String> keys = hashmap1.keySet();
for (String key : keys) {
System.out.println(key+"="+hashmap1.get(key));
}
}
}
输出结果:
?
?
|