Jakarta Commons Cookbook笔记(1)
Jakarta Commons Cookbook笔记
lang包
ReflectionToStringBuilder.toString()
例1.
ReflectionToStringBuilder.toString(newModel())
Model@14318bb[url=www.chengang.com.cn,port=80]
例2.
ReflectionToStringBuilder.toString(newModel(),ToStringStyle.MULTI_LINE_STYLE));
Model@14318bb[
url=www.chengang.com.cn
port=80
]
classModel{
Stringurl="www.chengang.com.cn";
intport=80;
}
ToStringBuilder.reflectionToString();
例1.
ToStringBuilder.reflectionToString(newModel());
Model@14318bb[url=www.chengang.com.cn,port=80]
改写类的三方法toString、hashCode、equals
classModel{
Stringurl="www.chengang.com.cn";
intport=80;
publicStringtoString(){
returnnewToStringBuilder(this).append("url",url).append("port",port).toString();
}
publicinthashCode(){
//17,37要求为质数
returnnewHashCodeBuilder(17,37).append(url).append(port).toHashCode();
// HashCodeBuilder.reflectionHashCode(this);
}
publicbooleanequals(Objecto){
booleanresult=false;
if(o!=null&&Model.class.isAssignableFrom(o.getClass())){
Modelm=(Model)o;
result=newEqualsBuilder().append(url,m.url).append(port,m.port).isEquals();
}
returnresult;
//EqualsBuilder.reflectionEquals(this,o);
}
}
CompareToBuilder.reflectionCompare(this,o);
public int compareTo(Object o){
return CompareToBuilder.reflectionCompare(this,o);
}
public int compareTo(Object o){
int result = -1;
if (o!=null && Model.class.isAssignableFrom(o.getClass()){
Model m = (Model)o;
result = new CompareToBuilder().append(url,m.url).append(port,m.port)
.toComparison();
}
return result;
}
打印数组
用commons的:ArrayUtils.toString();
用JDK的:Arrays.toString();
基础类型和包装类型的数组互转
Long[] objectArray = ArrayUtils.toObject(primitiveArray);
long[] primitiveArray = ArrayUtils.toprimitive(objectArray);
在数组中查找
boolean b = ArrayUtils.contains(stringArray, "glchengang");
int i = ArrayUtils.indexOf(stringArray, "glchengang"); //找不到返回-1
int l = ArrayUtils.lastIndexOf(stringArray, "glchengang");
多维数组转Map
Object[] array = new Object[][]{{"A", new Double(1.007)}, ... , {"F", new Double(1.007)}};
Map map = ArrayUtils.toMap(array);
Double d = map.get("A");