使用hashmap存储对象 并获取元素 祛除重复元素需要在类对象中重写hashcode和equal方法哦
2016-08-31 17:47
721 查看
这是主题部分
这是学生类
package com.heima.maptest; import java.util.HashMap; import java.util.Map; import com.heima.Student.Student; /** * 怎么用hashmap存储对象 * * @author fenuang * */ public class students { public static void main(String[] args) { // TODO Auto-generated method stub Map<Student, String> map = new HashMap<>(); map.put(new Student("张三", 23), "北京"); map.put(new Student("张三", 23), "上海"); map.put(new Student("李四", 24), "广州"); map.put(new Student("王五", 25), "深圳"); /* * 为确保键值的唯一性,即自己定义的类在set中存储的话,其hashcode值均不相同, 需要重新hashcode来确保相同时键值只有一个 * 还要重写equal方法. */ System.out.println(map); } }
这是学生类
package com.heima.Student; public class Student { private String name; private int 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; } /** * @param name * @param age */ public Student(String name, int age) { super(); this.name = name; this.age = age; } /** * */ public Student() { super(); // TODO Auto-generated constructor stub } @Override public String toString() { // TODO Auto-generated method stub // return "Person : [name=" + name + ", age = " + age + "]"; return "Person : [name = " + name + ", age = " + age + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Student other = (Student) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
相关文章推荐
- 使用HashSet 存储自定义对象,为什么需要重写hashCode()和equals()?
- HashMap将对象作为key为什么需要重写equals和hashcode方法
- 使用Set存储Object对象,重写equals和hashCode方法
- ndk多线程需要获取JNIEnv 或c通过类名+包名创建对象使用如下方法
- JQ使用陷阱,获取的元素要转成对象才可以使用JQ的方法
- java中hashMap使用一个对象作为key时,对key进行唯一性表达重写equals()方法
- Set是如何实现元素不重复的&重写equals()方法之后也必须重写hashCode()方法
- 对象作为 map 的 key 时,需要重写 equals 方法和 hashCode 方法
- HashMap中的key为什么不能为可变对象(除非重写它的hashcode方法和equals方法)
- HashMap什么时候重写hashcode和equals方法,为什么需要重写
- object对象重写equals方法时为什么需要重写hashCode方法
- 在重写了对象的equals方法后,还需要重写hashCode方法吗?
- Object中hashcode(),equal()方法需要重写的时期
- 【原创】关于java对象需要重写equals方法,hashcode方法,toString方法 ,compareto()方法的说明
- HashSet存储元素equals() hashCode()方法重写
- 在重写了对象的equals方法后,还需要重写hashCode方法吗?
- FMDB封装,用OC方法存储model,不用写SQL语句。使用runtime获取对象属性
- set实体泛型对象去重(重写实体hashCode、equal方法)
- 重写Java Object对象的hashCode和equals方法实现集合元素按内容判重
- 向HashSet集合存入对象,去除重复元素(覆写equals和hashCode方法)