黑马程序员技术交流社区
标题:
写的反射小实例,加载成功后的HashSet无法对重复对象判断...
[打印本页]
作者:
逆世界ylm
时间:
2014-12-19 21:45
标题:
写的反射小实例,加载成功后的HashSet无法对重复对象判断...
package com.ccsu.reflection;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.Properties;
public class Demo8 {
/**
* @param args
* @throws IOException
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException {
//hashCode方法的作用,对对象进行计算,当修改对象后hashcode会改变,再去操作会内存泄露
//小框架书写
FileInputStream fis = new FileInputStream("test.properties");
Properties p = new Properties();
p.load(fis);
fis.close();
String className = p.getProperty("className");
System.out.println(className);
Collection c = (Collection)Class.forName(className).newInstance();
PersonDemo p1 = new PersonDemo("小叶",20);
PersonDemo p2 = new PersonDemo("小李",25);
PersonDemo p3 = new PersonDemo("小王",24);
PersonDemo p4 = new PersonDemo("小叶",20);
PersonDemo p5 = new PersonDemo("小叶",20);
c.add(p4);
c.add(p3);
c.add(p2);
c.add(p1);
c.add(p5);
System.out.println(c.size());
}
}
class PersonDemo
{
public PersonDemo(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj)
{
if(!(obj instanceof Person))
return false;
PersonDemo p = (PersonDemo)obj;
if(this.name == p.name && this.age == p.age)
{
return true;
}
else
return false;
}
public int hashCode() {
return name.hashCode();
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
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;
}
}
复制代码
其中我的配置文件得到的是,HashSet,我的PersonDemo这个类中也写了hashcode和equal函数,为什麽得到的相同对象还是可以存到hashSet中呢??
作者:
董晗
时间:
2014-12-19 21:47
额,还没学到反射
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2