一
在不做編譯優化的情況下
例子
import java
class CEL {
void method (Vector vector) {
for (int i =
; //
}
}
更正
class CEL_fixed {
void method (Vector vector) {
int size = vector
for (int i =
; //
}
}
二
JVM為Vector擴充大小的時候需要重新創建一個更大的數組
通常
例子
import java
public class DIC {
public void addObjects (Object[] o) {
// if length >
for (int i =
v
}
}
public Vector v = new Vector(); // no initialCapacity
}
更正
自己設定初始大小
public Vector v = new Vector(
public Hashtable hash = new Hashtable(
參考資料
Dov Bulka
Techniques
三
程序中使用到的資源應當被釋放
例子
import java
public class CS {
public static void main (String args[]) {
CS cs = new CS ();
thod ();
}
public void method () {
try {
FileInputStream fis = new FileInputStream (
int count =
while (fis
count++;
System
fis
} catch (FileNotFoundException e
} catch (IOException e
}
}
}
更正
在最後一個catch後添加一個finally塊
參考資料
Peter Haggar:
Addison Wesley
四
例子
public class IRB
{
void method () {
int[] array
for (int i =
array
}
int[] array
for (int i =
array
}
}
}
更正
public class IRB
{
void method () {
int[] array
for (int i =
array
}
int[] array
System
}
}
參考資料
五
簡單的getter/setter方法應該被置成final
例子
class MAF {
public void setSize (int size) {
_size = size;
}
private int _size;
}
更正
class DAF_fixed {
final public void setSize (int size) {
_size = size;
}
private int _size;
}
參考資料
Warren N
Addison
六
如果左邊的對象的靜態類型等於右邊的
例子
public class UISO {
public UISO () {}
}
class Dog extends UISO {
void method (Dog dog
Dog d = dog;
if (d instanceof UISO) // always true
System
UISO uiso = u;
if (uiso instanceof Object) // always true
System
}
}
更正
刪掉不需要的instanceof操作
class Dog extends UISO {
void method () {
Dog d;
System
System
}
}
七
所有的類都是直接或者間接繼承自Object
例子
class UNC {
String _id =
}
class Dog extends UNC {
void method () {
Dog dog = new Dog ();
UNC animal = (UNC)dog; // not necessary
Object o = (Object)dog; // not necessary
}
}
更正
class Dog extends UNC {
void method () {
Dog dog = new Dog();
UNC animal = dog;
Object o = dog;
}
}
參考資料
Nigel Warren
for Effective Java
From:http://tw.wingwit.com/Article/program/Java/hx/201311/25979.html