看了一部分前辈的思想。有关代码的理解有相当的功力。
上代码
1。
package com.ywreflector;
public class ReflectPoint {
private int x;
public int y;
public String str1 = "ball";
public String str2 = "basketball";
public String str3 = "itcast";
public ReflectPoint(int x, int y) {
super();
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ReflectPoint other = (ReflectPoint) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
@Override
public String toString(){
return str1+":"+str2+":"+str3;
}
}
2。java project下新建一个config.properties文件。里面写上下面的一句话
className=java.util.HashSet
3。
package com.ywreflector;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Collection;
import java.util.Properties;
//ArrayList,HashSet比较,
//Hashcode分析
public class ReflectTest2 {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
InputStream ips=new FileInputStream("config.properties");
Properties props=new Properties();
props.load(ips);
ips.close();
//使用property文件
String className=props.getProperty("className");
Collection collections=(Collection)Class.forName(className).newInstance();
// Collection collections=new HashSet();
// Collection collections=new ArrayList();
ReflectPoint pt1=new ReflectPoint(3,3);
ReflectPoint pt2=new ReflectPoint(5,5);
ReflectPoint pt3=new ReflectPoint(3,3);
collections.add(pt1);
collections.add(pt2);
collections.add(pt3);
collections.add(pt1);
// //参与hashcode的参数不要修改,否则无法删除,最终会内存泄露
// pt1.y=7;
// collections.remove(pt1);
System.out.println(collections.size());
}
}