HashMap和HashSet去重的介绍
所有类都继承了Object类,Object中有个hashCode()方法(Integar,String等基本类型都重写了hashCode方法)hashCode方法能产生一个hash值HashMap和HashSet根据这个hash值是否相同,来去重
以基本类型为键值
private static void show1() {
Map<String,Students> map=new HashMap<>();
map.put("one",new Students("zhangsan","10"));
map.put("two",new Students("lisi","20"));
map.put("three",new Students("wangwu","30"));
map.put("four",new Students("zhaoliu","40"));
// System.out.println(map);
/*使用keySet()+forech遍历 */
for (String key : map.keySet()){
System.out.println(key+"="+map.get(key));
}
System.out.println("-------------------------------------------------");
/*使用entrySet()+forech遍历*/
for (Map.Entry<String,Students> entry: map.entrySet()) {
System.out.println(entry.getKey()+"="+entry.getValue());
}
以自定义类型为键值
Students类
public class Students {
private String name;
private String ages;
// @Override
// public int hashCode() {
//
// return Objects.hash(name, ages);
// }
...省略get set方法
}
以Students为键值放入
private static void show2() {
Map<Students,String> map=new HashMap<>();
map.put(new Students("zhangsan","10"),"one");
map.put(new Students("zhangsan","10"),"one");
map.put(new Students("lisi","20"),"two");
for (Students key : map.keySet()){
System.out.println(key+"="+map.get(key));
}
}
当Students没重写hashCode方法时 当Students重写了hashCode方法时
Map其它常用方法
remove(Object key) 返回值:移除的value值,没有对应的value返回null 如果存在一个键的映射关系,则将其从此映射中移除(可选操作)。
size() 返回值:int 返回此映射中的键-值映射关系数。
clear() 返回值:void 从此映射中移除所有映射关系(可选操作)。