Java经典用法总结
在Java编程中,有些知识并不能仅通过语言规范或者标准API文档就能学到的,本文为大家罗列。
一、实现
1、现equals()
classPerson{
Stringname;
intbirthYear;
byte[]raw;
publicbooleanequals(Objectobj){
if(!objinstanceofPerson)
returnfalse;
Personother=(Person)obj;
returnname.equals(other.name)
&&birthYear==other.birthYear
&&Arrays.equals(raw,other.raw);
}
publicinthashCode(){...}
}
- 参数必须是Object类型,不能是外围类。
- foo.equals(null)必须返回false,不能抛NullPointerException。(注意,nullinstanceof任意类总是返回false,因此上面的代码可以运行。)
- 基本类型域(比如,int)的比较使用==,基本类型数组域的比较使用Arrays.equals()。
- 覆盖equals()时,记得要相应地覆盖hashCode(),与equals()保持一致。
2、现hashCode()
classPerson{
Stringa;
Objectb;
bytec;
int[]d;
publicinthashCode(){
returna.hashCode()+b.hashCode()+c+Arrays.hashCode(d);
}
publicbooleanequals(Objecto){...}
}
- 当x和y两个对象具有x.equals(y)==true,你必须要确保x.hashCode()==y.hashCode()。
- 根据逆反命题,如果x.hashCode()!=y.hashCode(),那么x.equals(y)==false必定成立。
- 你不需要保证,当x.equals(y)==false时,x.hashCode()!=y.hashCode()。但是,如果你可以尽可能地使它成立的话,这会提高哈希表的性能。
- hashCode()最简单的合法实现就是简单地return0;虽然这个实现是正确的,但是这会导致HashMap这些数据结构运行得很慢。
3、实现compareTo()
classPersonimplementsComparable<Person>{
StringfirstName;
StringlastName;
intbirthdate;
//ComparebyfirstName,breaktiesbylastName,finallybreaktiesbybirthdate
publicintcompareTo(Personother){
if(firstName.compareTo(other.firstName)!=0)
returnfirstName.compareTo(other.firstName);
elseif(lastName.compareTo(other.lastName)!=0)
returnlastName.compareTo(other.lastName);
elseif(birthdate<other.birthdate)
return-1;
elseif(birthdate>other.birthdate)
return1;
else
return0;
}
}
总是实现泛型版本Comparable而不是实现原始类型Comparable。因为这样可以节省代码量和减少不必要的麻烦。
只关心返回结果的正负号(负/零/正),它们的大小不重要。
Comparator.compare()的实现与这个类似。
4、实现clone()
classValuesimplementsCloneable{
Stringabc;
doublefoo;
int[]bars;
Datehired;
publicValuesclone(){
try{
Valuesresult=(Values)super.clone();
result.bars=result.bars.clone();
result.hired=result.hired.clone();
returnresult;
}catch(CloneNotSupportedExceptione){//Impossible
thrownewAssertionError(e);
}
}
}
- 使用super.clone()让Object类负责创建新的对象。
- 基本类型域都已经被正确地复制了。同样,我们不需要去克隆String和BigInteger等不可变类型。
- 手动对所有的非基本类型域(对象和数组)进行深度复制(deepcopy)。
- 实现了Cloneable的类,clone()方法永远不要抛CloneNotSupportedException。因此,需要捕获这个异常并忽略它,或者使用不受检异常(uncheckedexception)包装它。
- 不使用Object.clone()方法而是手动地实现clone()方法是可以的也是合法的。
二、预防性检测
1、预防性检测(Defensivechecking)数值
intfactorial(intn){
if(n<0)
thrownewIllegalArgumentException("Undefined");
elseif(n>=13)
thrownewArithmeticException("Resultoverflow");
elseif(n==0)
return1;
else
returnn*factorial(n-1);
}
- 不要认为输入的数值都是正数、足够小的数等等。要显式地检测这些条件。
- 一个设计良好的函数应该对所有可能性的输入值都能够正确地执行。要确保所有的情况都考虑到了并且不会产生错误的输出(比如溢出)。
2、预防性检测对象
intfindIndex(List<String>list,Stringtarget){
if(list==null||target==null)
thrownewNullPointerException();
...
}
- 不要认为对象参数不会为空(null)。要显式地检测这个条件。
3、预防性检测数组索引
voidfrob(byte[]b,intindex){
if(b==null)
thrownewNullPointerException();
if(index<0||index>=b.length)
thrownewIndexOutOfBoundsException();
...
}
不要认为所以给的数组索引不会越界。要显式地检测它。
4、预防性检测数组区间
voidfrob(byte[]b,intoff,intlen){
if(b==null)
thrownewNullPointerException();
if(off<0||off>b.length
||len<0||b.length-off<len)
thrownewIndexOutOfBoundsException();
...
}
不要认为所给的数组区间(比如,从off开始,读取len个元素)是不会越界。要显式地检测它。
三、数组
1、填充数组元素
使用循环:
//Filleachelementofarray'a'with123 byte[]a=(...); for(inti=0;i<a.length;i++) a[i]=123; (优先)使用标准库的方法: Arrays.fill(a,(byte)123);
2、复制一个范围内的数组元素
使用循环:
//Copy8elementsfromarray'a'startingatoffset3 //toarray'b'startingatoffset6, //assuming'a'and'b'aredistinctarrays byte[]a=(...); byte[]b=(...); for(inti=0;i<8;i++) b[6+i]=a[3+i]; (优先)使用标准库的方法: System.arraycopy(a,3,b,6,8);
3、调整数组大小
使用循环(扩大规模):
//Makearray'a'largertonewLen byte[]a=(...); byte[]b=newbyte[newLen]; for(inti=0;i<a.length;i++)//GoesuptolengthofA b[i]=a[i]; a=b;
使用循环(减小规模):
//Makearray'a'smallertonewLen byte[]a=(...); byte[]b=newbyte[newLen]; for(inti=0;i<b.length;i++)//GoesuptolengthofB b[i]=a[i]; a=b;
(优先)使用标准库的方法:
1a=Arrays.copyOf(a,newLen);
4、把4个字节包装(packing)成一个int
intpackBigEndian(byte[]b){
return(b[0]&0xFF)<<24
|(b[1]&0xFF)<<16
|(b[2]&0xFF)<<8
|(b[3]&0xFF)<<0;
}
intpackLittleEndian(byte[]b){
return(b[0]&0xFF)<<0
|(b[1]&0xFF)<<8
|(b[2]&0xFF)<<16
|(b[3]&0xFF)<<24;
}
5、把int分解(Unpacking)成4个字节
byte[]unpackBigEndian(intx){
returnnewbyte[]{
(byte)(x>>>24),
(byte)(x>>>16),
(byte)(x>>>8),
(byte)(x>>>0)
};
}
byte[]unpackLittleEndian(intx){
returnnewbyte[]{
(byte)(x>>>0),
(byte)(x>>>8),
(byte)(x>>>16),
(byte)(x>>>24)
};
}
总是使用无符号右移操作符(>>>)对位进行包装(packing),不要使用算术右移操作符(>>)。
以上就是本文的全部内容,希望对大家的学习有所帮助。