20:String的连接用StringBuffer,减少生成的对象,有助于提高效率。
public String attachStr(String[] strDim) {
StringBuffer rtnStrBuff = new StringBuffer();
for(int i = 0 ; i < strDim.length ; i++) {
//StringBufferによる連結
rtnStrBuff.append(strDim[i]);
}
return rtnStrBuff.toString();
}
21:尽量写成”xxx”.equals(String)而不是String.equals(“XXX”)。
后者要判断String是否为null,前者更简洁明了。
22:在自定义例外的时候,继承Exception类,而不是Error或Throwable。因为Error类通常用于系统内严重的硬件错误。并且在多数情况下,不要把自定义的例外类作为运行时例外类RuntimeException子类。另外,自定义例外类的类名常常以Exception结尾。 public class SampleAaaException extends Exception{ ←OK public class SampleBbbException extends IOException{ ←NG public class SampleCccException
extends RuntimeException{ ←NG
23:在catch语句中不声明Exception,RuntimeException。 public class BadSample{ public void badSampleMethod(){ try { System.in.read(); } catch(Exception e){ // 違反 e.printStackTrace(); } }
}
public class FixedSample{
public void fixedSampleMethod() {
try {
System.in.read();
} catch (IOException e) { // 修正済み
e.printStackTrace();
}
}
}
同样,也不要直接throw那些上层的Exception,应throw具体的Exception
24:对于一格try有多个catch与他对应得场合,catch块的顺序应由特殊到一般。
25:不要在循环内做例外处理,不要有空的catch块,catch快中不要有return,这样抛出去的异常,在元方法中截不到。
26:建议使用ArrayList,HashMap,Iterator,但是ArrayList,HashMap不是同步,所以在多线程的时候不安全,这时,可以使用java.util.Collections的synchronizedList和synchronizedMap方法。
List list = Collections.synchronizedList(new ArrayList());
...
synchronized(list) {
Iterator i = list.iterator(); // Must be in synchronized block
while (i.hasNext())
foo(i.next());
}
27:如果涉及到堆栈,队列等操作,应该考虑用List,对于需要快速插入,删除元素,应该使用LinkedList,如果需要快速随机访问元素,应该使用ArrayList。 如果程序在单线程环境中,或者访问仅仅在一个线程中进行,考虑非同步的类,其效率较高,如果多个线程可能同时操作一个类,应该使用同步的类。 要特别注意对哈希表的操作,作为key的对象要正确复写equals和hashCode方法。 尽量返回接口而非实际的类型,如返回List而非ArrayList,这样如果以后需要将ArrayList换成LinkedList时,客户端代码不用改变。这就是针对抽象编程。
28:如果想做比较准确的精度计算,可以使用BigDecimal。基本的数值类型的类型转换过程中,不要由高精度的转换成低精度的,防止精度丢失。 public class CastTest{ public static void main(String[] args){ double doubleType = 2.75; int intType = (int)doubleType; // doubleをintにキャスト System.out.println("double : " + doubleType); System.out.println("int : " + intType); } } 実行結果は以下のとおりである: double : 2.75
int : 2
在实数比较的时候,由于精度问题,用 例1: if( abs(a-b) < 1.0e-6 ) { 。。。 } 例2: if( a-b > -1.0e-6 ) { 。。。
} 来代替 例1: if( a == b ) { 。。。 } 例2: if( a > b ) { 。。。
}
29:在做文件读写操作的时候,不要在try中关闭流,这样会产生出现异常而没有关闭流的情况,应在final中关闭。
30:一个良好的JDBC的sample。 public class Sample { // ... public void searchSomething(...){ ... Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = ConnectionManager.getConnection( ); stmt = conn.prepareStatement( sql ); rs = stmt.executeQuery( ); ... } catch ( ... ) { ... } finally { if ( rs != null ){ try { rs.close(); } catch ( Exception e ) { ... // logなど } } if ( stmt != null ){ try { stmt.close(); } catch ( Exception e ) { ... // logなど } } if ( conn != null ){ try { conn.close(); } catch ( Exception e ) { ... // logなど } } } ... } }
(待以后补充) 望能共同提高! 
|