- 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中呢??
|