1. Mybatis多条件查询尽量别写where 1=1

用where 1=1目的在于不管用户查询条件是什么,有还是没有,都可以保证查询正常进行,不出现漏where的情况,但效率低,数据库无法使用索引优化,造成全表扫描;

可以在where标签中判断字段是否存在,是否需要作为查询条件

2. 获取Map的key用keySet(),获取key和value用entrySet()

  1. /*获取value*/
  2. HashMap<String, String> hashMap = new HashMap<>();
  3. /*反例*/
  4. for (String key : hashMap.keySet()){
  5. String value = hashMap.get(key);
  6. }
  7. /*正例,效率高*/
  8. for (java.util.Map.Entry<String, String> entry : hashMap.entrySet()){
  9. String key = entry.getKey();
  10. String value = entry.getValue();
  11. }

3. 校验List是否为空用isEmpty(),不要用size()

        /*校验List集合是否为空*/
        ArrayList<String> arrayList = new ArrayList<>();
        /*反例*/
        if (arrayList.size() == 0){
            return;
        }

        /*正例,易读,效率高*/
        if (arrayList.isEmpty()){
            return;
        }

4. 初始化集合时尽量指定大小

        /*往集合添加元素*/
        int[] arr = new int[]{1,2,3,1,1,12,4};
        /*反例*/
        ArrayList<Integer> arrayList = new ArrayList<>();
        for (int val : arr){
            arrayList.add(val);
        }

        /*正例,可以减少扩容次数*/
        ArrayList<Integer> arrayList1 = new ArrayList<>(arr.length);
        for (int val : arrayList1){
            arrayList1.add(val);
        }

5. 循环拼接字符串时用StringBuilder

        /*循环拼接字符串*/
        /*反例*/
        String str = "";
        for (int i = 0; i < 10; i++) {
            str += i;
        }

        /*正例*/
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 10; i++) {
            stringBuilder.append(i);
        }

6. 转化字符串用valueOf(),别用” “ +

        /*转化字符串*/
        int i = 200;
        /*反例*/
        String val = "" + i;
        /*正例,效率高*/
        String val2 = String.valueOf(i);

7. 方法返回值是数组或集合时,如果返回是null,替换成空数组或者空集合

    /*反例,返回null*/
    public static int[] getInt(){
        return null;
    }
    public static List<Integer> getList(){
        return null;
    }
    public static java.util.Map<Integer, String> getMap(){
        return null;
    }

    /*正例,返回空数组或空集合*/
    public static int[] getInt2(){
        return new int[0];
    }
    public static List<Integer> getList2(){
        return Collections.EMPTY_LIST;
    }
    public static java.util.Map<Integer, String> getMap2(){
        return Collections.EMPTY_MAP;
    }

8. 用equals()比较时,尽量用确定有的值作为调用方

    /*反例*/
    public static boolean getFile(String fileName){
        if (fileName.equals("地图")){
            return true;
        }
        return false;
    }

    /*正例,避免空指针异常*/
    public static boolean getFile2(String fileName){
        // 或者用 Objects.equals("地图", fileName);
        if ("地图".equals(fileName)){
            return true;
        }
        return false;
    }