在Hashmap中 判断对象重复是 hashcode值和equals方法.
都重写了,第一种方法不知道为什么不正确. <String,Student>
第二种可以. <Student,String>
求大神解读
- import java.util.HashMap;
- import java.util.Set;
- /*
- * HashMap存储键和值。并遍历。
- * 键:String 学号
- * 值:Student (name,age)
- *
- * 特有需求:两个对象的成员变量值如果都相同。我们则认为是同一个对象。
- */
- public class HashMapDemo2 {
- public static void main(String[] args) {
- HashMap<String,Student> hm = new HashMap<String,Student>();
-
- hm.put("1",new Student("Google",5));
- hm.put("2", new Student("lenovo",10));
- hm.put("3", new Student("apple",8));
- hm.put("4", new Student("apple",8));
- hm.put("5", new Student("apple",8));
- //输出不能去除重复
- Set<String> set = hm.keySet();
- for(String key:set){
- Student value = hm.get(key);
- System.out.println(key+"--"+value.getName()+"---"+value.getAge());
- }
-
- HashMap<Student,String> hm2 = new HashMap<Student,String>();
- hm2.put(new Student("google",5), "1");
- hm2.put(new Student("google",5), "1");
- hm2.put(new Student("google",5), "1");
- hm2.put(new Student("lenovo",7), "2");
- hm2.put(new Student("lenovo",7), "2");
- //正常,可以去重复
- Set<Student> set2 = hm2.keySet();
- for(Student key : set2){
- String value = hm2.get(key);
- System.out.println(key.getName()+"---"+key.getAge()+"---"+value);
- }
- }
- }
复制代码
- public class Student {
- private String name;
- private int age;
- public Student(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public int hashCode() {
- return this.name.hashCode() + this.age * 3;
- }
- //参数为object 才行?
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if(!(obj instanceof Student)){
- return false;
- }
- Student stu = (Student)obj;
- return this.name.equals(stu.name) && this.age == stu.age;
- }
- }
复制代码
|
|