1 prefer returning empty collections but not null : can avoid many if null tests
2 String operation in loop : try to use StringBuilder and StringBuffer because String is immutable
3 try your best to avoid create unused object ---- creating object is the most expensive
4 when size is fixed, try to use array but not ArrayList --- array is more fast than arrayList
5 exit() is priory than finally : when exit() is called, finally() will not be reached
6 is odd number(奇数) ?
return num%2 == 1 --> what about negative numbers ?
so better solution is : return (nums&1) == 1
7 three tips for memory : a. use finally b. release connection once after inquire (查询) DB
c.remember to release instance of static members
8 give attention to avoid deadlock : sometimes it's just a order of calling two methods
9 want to calculate the running time ?
System.currentTimeMillis() : is related to a absolute number (1970/01/01...), faster than nanoTime.
System.nanoTime() : not related to any time point, more accurate(精确 millis vs nano)\
10 float or double ?
float : 4 bytes : 7 significant digits(有效数字)
double : 8 bytes : 14
11 Exponentiation (幂运算) a^N
Java use xor to calculate Exponentiation
there are two ways :
multiply:
res = a*a;
res*=a;
.....
Math.pow(a,N) ---> too slow, try to use multiply
12 JSON is easy to use :
JSONbject obj;
obj.put("key","value")//{key : value}
array = new JSONArray()
array.add(value1);
array.add(value2)
array.add(value3)
...
obj.put("arrayKey", array)//{key : [value1,v2,v3...]}
============================================
FileReader reader = ....
JSONParser jsonParser = new ...
JSONObject obj = (JSONObject)jsonParser.parse(FileReader)
12 search sub string : String.indexOf() : -1 for not found
13 when we known not found returns -1, when using if , it's better to use
if(i<0) rather than if(i == -1) --> who knows it will not return -2 ?!
14 SOLID : one class just do one thing!
15 less than 10 classes in a package
16 less than 50 methods in a class
17 less than 200 lines in a file
18 use equals() rather than ==
19 in "if" put const before the variable if("const".equals(s))
20 try not to use float and double as possible
21 use final for all methods, parameters of method and variables you created !
22 always add default in switch
23 use {}, even one line, particularly for switch case
No comments:
Post a Comment