黑马程序员技术交流社区
标题:
TreeMap中去除重复对象不对?
[打印本页]
作者:
山里孩子
时间:
2015-4-8 22:11
标题:
TreeMap中去除重复对象不对?
在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;
}
}
复制代码
作者:
关山明月
时间:
2015-4-8 22:56
Map集合的
键
是唯一的!
因为第一种方式的键是String类型的,所以如果集合的键值出现相同的话,值会覆盖之前的值,但是你往集合中插入的键没有相同的,是"1","2","3","4","5" 没有相同的,后面的值Student类对象可以相同。
第二种方式的键是Student类型的,有相同的,所以添集合中添加的时候,会根据HashCode() 和 equals() 来判断是否相同。相同,则覆盖键对应的旧值。
作者:
jayden
时间:
2015-4-8 23:09
不知道为什么没有重写HashCode(),不会写的话就自动生成啊,这个要写的
作者:
chenlong
时间:
2015-4-8 23:12
不对吧,hashcoed里面的值是唯一的
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2