通用程序设计

2018-02-19  本文已影响0人  李军_6eaa
最小化local variables的范围
for 循环和while循环相比,有哪些好处?
for (Iterator<Element> i = c.iterator(); i.hasNext(); ) {
    Element e = i.next();
    ... // Do something with e and i
}
...

// Compile-time error - cannot find symbol i
for (Iterator<Element> i2 = c2.iterator(); i.hasNext(); ) {
    Element e2 = i2.next();
    ... // Do something with e2 and i2
} 
Iterator<Element> i = c.iterator();
while (i.hasNext()) {
    doSomething(i.next());
}
...
Iterator<Element> i2 = c2.iterator();
while (i.hasNext()) {             // BUG!
    doSomethingElse(i2.next());
}
for (int i = 0, n = expensiveComputation(); i < n; i++) {
    ... // Do something with i;
}
优先使用for-each loops,而不是传统的for loops
懂得使用the libraries
// Common but deeply flawed!
static Random rnd = new Random();
static int random(int n) {
    return Math.abs(rnd.nextInt()) % n;
}
// just use
Random.nextInt(int)
// for Java 7
use ThreadLocalRandom, not Random
// for fork join pools and parallel streams
use SplittableRandom 
如果需要exact answer,请不要使用float 和 double类型
说说Java的两种类型系统
说说primitives 和 boxed primitives的区别
// error! 由于==符号,(new Integer(42), new Integer(42))比较,会返回1
Comparator<Integer> naturalOrder =
    (i, j) -> (i < j) ? -1 : (i == j ? 0 : 1);
//right way
Comparator<Integer> naturalOrder = (iBoxed, jBoxed) -> {
“int i = iBoxed, j = jBoxed; // Auto-unboxing
    return i < j ? -1 : (i == j ? 0 : 1);
};
public class Unbelievable {
    static Integer i;

    public static void main(String[] args) {
        if (i == 42)  //NullPointerException
            System.out.println("Unbelievable");
    }
}
public static void main(String[] args) {
    Long sum = 0L;
    for (long i = 0; i < Integer.MAX_VALUE; i++) {
        sum += i; //重复的拆箱和装箱,影响性能
    }
    System.out.println(sum);
}
什么时候必须使用boxed primitives
当其他类型更适合时,请不要使用strings类型
// Inappropriate use of string as aggregate type
String compoundKey = className + "#" + i.next(); 
小心String concatenation operator (+)的性能
使用interfaces来引用objects
// Good - uses interface as type
Set<Son> sonSet = new LinkedHashSet<>();
// Bad - uses class as type!
LinkedHashSet<Son> sonSet = new LinkedHashSet<>();
有哪些情况适合使用具体类来引用objects
优先使用 interfaces 而不是 reflection
reflection的缺点
怎么结合使用 interfaces 和 reflection
// Reflective instantiation with interface access
public static void main(String[] args) {
    // Translate the class name into a Class object
    Class<? extends Set<String>> cl = null;
    try {
        cl = (Class<? extends  Set<String>>)  // Unchecked cast!
                Class.forName(args[0]);
    } catch (ClassNotFoundException e) {
        fatalError("Class not found.");
    }
    // Get the constructor
    Constructor<? extends Set<String>> cons = null;
    try {
        cons = cl.getDeclaredConstructor();
    } catch (NoSuchMethodException e) {
        fatalError("No parameterless constructor");
    }
    // Instantiate the set
    Set<String> s = null;
    try {
        s = cons.newInstance();
    } catch (IllegalAccessException e) {
        fatalError("Constructor not accessible");
    } catch (InstantiationException e) {
        fatalError("Class not instantiable.");
    } catch (InvocationTargetException e) {
        fatalError("Constructor threw " + e.getCause());
    } catch (ClassCastException e) {
        fatalError("Class doesn't implement Set");
    }
    // Exercise the set
    s.addAll(Arrays.asList(args).subList(1, args.length));
    System.out.println(s);
}
private static void fatalError(String msg) {
    System.err.println(msg);
    System.exit(1);
}
使用native methods,要谨慎
代码优化,要谨慎
坚持公认的命名惯例
上一篇 下一篇

猜你喜欢

热点阅读