java面试知识点三(HashMap输出及保持元素唯一性)

Student类:
public class Student {
private int s_id;
private String name;
private int age;
private String description;
public int hashCode(){
return name.hashCode()+age*23;
}
public boolean equals(Object obj){
// 同一个对象放两次就直接返回true
 if (this == obj)
  return true;

 // 判断是不是Student类型
 if (!(obj instanceof Student))
  return false;
 Student s = (Student) obj;

 // 姓名和年龄都相同视为重复
 return this.name.equals(s.name) && this.age == s.age;
}
public Student(){}
public Student(int s_id, String name, int age, String description) {
super();
this.s_id = s_id;
this.name = name;
this.age = age;
this.description = description;
}
@Override
public String toString() {
return "Student [s_id=" + s_id + ", name=" + name + ", age=" + age
+ ", description=" + description + "]";
}
//setter and getter....
}



main函数:
public static void main(String[] args) throws Exception {
Student s1 = new Student(1,"zqh",22,"deszqh");
Student s2 = new Student(2,"gkn",23,"desgkn");
Student s3 = new Student(3,"lbb",24,"deslbb");
Student s4 = new Student(1,"zqh",22,"deszqh");
Map<Student,String> map = new HashMap<>();
map.put(s1, "01");
map.put(s2, "02");
map.put(s3, "03");
map.put(s4, "04");
//第一种遍历方式:效率高,以后一定要用这种方式(entrySet来遍历)
System.out.println("entrySet来遍历:");
Iterator<Map.Entry<Student,String>> it = map.entrySet().iterator();
while(it.hasNext())
{
Map.Entry<Student,String> entry = it.next();
System.out.print("键:"+ entry.getKey()+" ");
System.out.println("值:"+ entry.getValue());
}
//第二种,效率低,少用(keySet来遍历)
System.out.println("keySet来遍历:");
Iterator<Student> it2 = map.keySet().iterator();//迭代key值
while(it2.hasNext())
{
Student key = it2.next();
System.out.println("键:"+key+" 值: "+map.get(key));
}
}


输出情况:(1)上面代码中,若直接运行,会输出3个,因为判断的是key值(Student的引用或内容),在这里是复写hashCode和equals方法比较的是Student中的内容。
          (2)上面代码中,若注释掉hashCode和equals方法,则会输出4个,即按默认的hashCode和equals方法来比较,找不到重复的。
 (3)上面代码中,若仅把Student s4 = new Student(1,"zqh",22,"deszqh");改为 Student s4 = new Student(1,"zqh2",22,"deszqh");即仅仅变了名字,输出4个,因为equals方法返回false,不相等,不认为同样的对象。
 (4)上面代码中,若把Student s4 = new Student(1,"zqh",22,"deszqh");改为 Student s4 = new Student(1,"zqh2",22,"deszqh");同时注释Student中的hashCode和equals方法,也输出4个。
遍历情况:注意的是HashMap和HashSet遍历相差不大。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bboyzqh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值