package map;
import java.util.*;
public class hashmapTest {
public static void main(String[] args) {
HashMap<student,String> h1 =new HashMap<>();
System.out.println("-------------添加元素-----------------");
student s1 =new student("棋棋",01);
student s2 =new student("瑶瑶",02);
student s3 =new student("杨杨",03);
h1.put(s1,"广州");
h1.put(s2,"广州");
h1.put(s3,"广州");
h1.put(new student("瑶瑶",02),"广州");//在没有重写hashCode()方法和equals()方法是可以加进去的。
System.out.println("集合h1的长度为:"+h1.size());
System.out.println(h1);
System.out.println("-------------删除元素-----------------");
h1.remove(s3);//根据键值删除
System.out.println("集合h1的长度为:"+h1.size());
System.out.println(h1);
System.out.println("-------------遍历元素-----------------");
System.out.println("-------------使用keySet()遍历-----------------");
for (student a:h1.keySet()) {
System.out.println(a.toString()+"-----"+h1.get(a));
}
System.out.println("-------------使用entrySet()方法遍历-----------------");
Set<Map.Entry<student, String>> entries = h1.entrySet();
for (Map.Entry<student,String> a:entries) {
System.out.println(a.getKey()+"-----"+a.getValue());
}
System.out.println("-------------判断-----------------");
//重写hashCode()方法和equals()方法之前是不包含的
System.out.println("键里面是否包含学号为02的瑶瑶:"+h1.containsKey(new student("瑶瑶", 02)));
System.out.println("键里面是否包含s3对象:"+h1.containsKey(s3));
System.out.println("值里面是否包含八戒:"+ h1.containsValue("八戒"));
System.out.println("值里面是否包含广州:"+ h1.containsValue("广州"));
}
}
class student{
String name;
int num;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public student() {
}
public student(String name, int num) {
this.name = name;
this.num = num;
}
@Override
public String toString() {
return "student{" +
"name='" + name + '\'' +
", num=" + num +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
student student = (student) o;
return num == student.num &&
Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, num);
}
}
输出结果:
-------------添加元素-----------------
集合h1的长度为:3
{student{name='瑶瑶', num=2}=广州, student{name='棋棋', num=1}=广州, student{name='杨杨', num=3}=广州}
-------------删除元素-----------------
集合h1的长度为:2
{student{name='瑶瑶', num=2}=广州, student{name='棋棋', num=1}=广州}
-------------遍历元素-----------------
-------------使用keySet()遍历-----------------
student{name='瑶瑶', num=2}-----广州
student{name='棋棋', num=1}-----广州
-------------使用entrySet()方法遍历-----------------
student{name='瑶瑶', num=2}-----广州
student{name='棋棋', num=1}-----广州
-------------判断-----------------
键里面是否包含学号为02的瑶瑶:true
键里面是否包含s3对象:false
值里面是否包含八戒:false
值里面是否包含广州:true
需要注意的是: 有无重写hashCode()方法和equals()方法对添加、删除、判断元素有很大的影响。