1.工具类或者常量类里面的方法都是静态的,建议直接用类名调用,不用创建对象,所以将构造方法私有化,禁止创建对象
1 2 3 4 5 6 7 8 9 10 11 12 13
| //error example: public class StringUtils{ /** * 判断一个字符串是否为英文中文或数字 * * @param str * @return */ public static boolean isLetterDigitOrChinese( String str ) { String regex = "^[a-z0-9A-Zu4e00-u9fa5]+$"; return str.matches( regex ); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| //right example: public class StringUtils{ //添加构造私有构造方法 private StringUtils{ } /** * 判断一个字符串是否为英文中文或数字 * * @param str * @return */ public static boolean isLetterDigitOrChinese( String str ) { String regex = "^[a-z0-9A-Zu4e00-u9fa5]+$"; return str.matches( regex ); } }
|
2.NPE(空指针异常)-equals
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| //error String testString="abc"; if(testString.equals("abc")){ 大专栏 java代码审查v class="line">}else{ } //right String testString="abc"; if("abc".eqauls(testString)){ //code }else{ //code }
|
3.map list 新建 (java 1.7 )
1 2 3 4 5 6 7
| // Noncompliant List<String> strings = new ArrayList<String>(); Map<String,List<Integer>> map = new HashMap<String,List<Integer>>(); //Compliant Solution List<String> strings = new ArrayList<>(); Map<String,List<Integer>> map = new HashMap<>();
|
4.使用isEmpty 来判断集合是否为空
1 2 3 4 5 6 7 8 9
| //Noncompliant if(data.size==0){ } //compliant if(data.isEmpty){ }
|
5.数组定义 (“[]” 在变量名字前面)
1 2 3 4 5
| //Noncompliant int arr[]={}; //compliant int[] arr={};
|
6.字符串转换为数字
1 2 3 4 5 6
| //Noncompliant String numString="12222222"; long numLong=Long.valueOf(numString); //compliant String numString="12222222"; long posNum=Long.parseLong( posMap.get( "num" ).toString());
|
7.公共静态成员应该加上final,也就是public static final 一般不分家