]; for (int i = 0; i < array2.length; i++) { array2 [i] = array1 [i]; } } // Violation
}
更正: public class IRB { void method () { int[] array1 = new int [100]; for (int i = 0; i < array1.length; i++) { array1 [i] = i; } int[] array2 = new int [100]; System.arraycopy(array1, 0, array2, 0, 100); } } 参考资料: cs.cmu.edu/~jch/java/speed.html
方法变成” 五、 让访问实例内变量的 getter/setter 方法变成”final” ”
简单的 getter/setter 方法应该被置成 final, 这会告诉编译器, 这个方法不会被重载, 所以,可以变成”inlined” 例子: 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. and Bishop P. (1999), "Java in Practice", p. 4-5 Addison-Wesley, ISBN 0-201-36065-9
六、 避免不需要的 instanceof 操作
如果左边的对象的静态类型等于右边的,instanceof 表达式返回永远为 true。 例子: public class UISO { public UISO () {} } class Dog extends UISO {
void method (Dog dog, UISO u) { Dog d = dog; if (d instanceof UISO) // always true. System.out.println("Dog is a UISO"); UISO uiso = u; if (uiso instanceof Object) // always true. System.out.println("uiso is an Object"); } } 更正: 删掉不需要的 instanceof 操作。 class Dog extends UISO { void method () { Dog d; System.out.println ("Dog is an UISO"); System.out.println ("UISO is an UISO"); } }
七、 避免不需要的造型操作
所有的类都是直接或者间接继承自 Object。同样,所有的子类也都隐含的“等于” 其父类。那么,由子类造型至父类的操作就是不必要的了。
例子: class UNC { String _id = "UNC"; } class Dog extends UNC { void method () { Dog dog = new Dog (); UNC animal = (UNC)dog; Object o = (Object)dog; } } 更正: class Dog extends UNC { void method () { Dog dog = new Dog(); UNC animal = dog; Object o = dog; } } // not necessary. // not necessary.