常用Java代码片段

检查空对象

1
2
3
if (Objects.isNull(obj)) {
    return null;
}

检查字符串为空

1
2
3
if (Objects.isNull(string) || string.isEmpty()) {
    return null;
}

检查列表为空

1
2
3
if (CollectionUtils.isEmpty(list)) {
    return Collections.emptyList();
}

检查对象相等

1
Objects.equals(name, thisName);

Map遍历

当循环中只需要获取Map 的主键key时,迭代keySet() 是正确的;但是,当需要主键key 和取值value 时,迭代entrySet() 才是更高效的做法,其比先迭代keySet() 后再去通过get 取值性能更佳。

1
2
3
4
5
6
//Map 获取key & value:
HashMap<String, String> map = new HashMap<>();
for (Map.Entry<String,String> entry : map.entrySet()){
 String key = entry.getKey();
 String value = entry.getValue();
}

初始化集合尽量指定容量大小

尽量在初始化时指定集合的大小,能有效减少集合的扩容次数,因为集合每次扩容的时间复杂度很可能时O(n),耗费时间和性能。

1
2
3
4
5
6
7
//初始化list,往list 中添加元素:
int[] arr = new int[]{1,2,3,4};
//指定集合list 的容量大小
List<Integer> list = new ArrayList<>(arr.length);
for (int i : arr){
    list.add(i);
}

使用StringBuilder拼接字符串

一般的字符串拼接在编译期Java 会对其进行优化,但是在循环中字符串的拼接Java 编译期无法执行优化,所以需要使用StringBuilder 进行替换。

1
2
3
4
5
6
7
8
9
//在循环中拼接字符串
String str1 = "Love";
String str2 = "Courage";
String strConcat = str1 + str2;  //Java 编译器会对该普通模式的字符串拼接进行优化
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++){
   //在循环中,Java 编译器无法进行优化,所以要手动使用StringBuilder
    sb.append(i);
}

在频繁调用Collections.contains方式时使用Set

在Java 集合类库中,List的contains 方法普遍时间复杂度为O(n),若代码中需要频繁调用contains 方法查找数据则先将集合list 转换成HashSet 实现,将O(n) 的时间复杂度将为O(1)。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
//频繁调用Collection.contains()
List<Object> list = new ArrayList<>();
Set<Object> set = new HashSet<>();
set.addAll(list);
for (int i = 0; i <= Integer.MAX_VALUE; i++){
    //时间复杂度为O(1)
    if (set.contains(i)){
        System.out.println("list contains "+ i);
    }
}

使用静态代码块给静态成员变量赋值

对于集合类型的静态成员变量,应该使用静态代码块赋值,而不是使用集合实现来赋值。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
/赋值静态成员变量
private static Map<String, Integer> map = new HashMap<String, Integer>();
static {
    map.put("Leo",1);
    map.put("Family-loving",2);
    map.put("Cold on the out side passionate on the inside",3);
}

private static List<String> list = new ArrayList<>();
static {
    list.add("Sagittarius");
    list.add("Charming");
    list.add("Perfectionist");
}

工具类中构造函数定义为private

工具类是一堆静态字段和函数的集合,其不应该被实例化;但是,Java 为每个没有明确定义构造函数的类添加了一个隐式公有构造函数,为了避免不必要的实例化,应该显式定义私有构造函数来屏蔽这个隐式公有构造函数。

1
2
3
4
5
6
7
8
9
public class PasswordUtils {
//工具类构造函数

//定义私有构造函数来屏蔽这个隐式公有构造函数
private PasswordUtils(){}
public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";
public static String encryptPassword(String aPassword) throws IOException {
    return new PasswordUtils(aPassword).encrypt();
}

转换为字符串使用String.valueOf

1
2
3
4
//把其它对象或类型转化为字符串:
int num = 520;
// String.valueOf() 效率更高
String strLove = String.valueOf(num);

返回空数组和集合而不是null

若程序运行返回null,需要调用方强制检测null,否则就会抛出空指针异常;返回空数组或空集合,有效地避免了调用方因为未检测null 而抛出空指针异常的情况,还可以删除调用方检测null 的语句使代码更简洁。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
//返回空数组和空集
public static Result[] getResults() {
    return new Result[0];
}

public static List<Result> getResultList() {
    return Collections.emptyList();
}

public static Map<String, Result> getResultMap() {
    return Collections.emptyMap();
}

避免使用BigDecimal(double)方法

BigDecimal(double) 存在精度损失风险,在精确计算或值比较的场景中可能会导致业务逻辑异常。

1
BigDecimal bigDecimal1 = bigDecimal.valueOf(0.11D);

string.split(String reg)参数关键字需要转译

使用字符串String 的plit 方法时,传入的分隔字符串是正则表达式,则部分关键字(比如 .[]()| 等)需要转义。

  • 正确写法

    1
    2
    3
    4
    5
    6
    7
    
    // . 需要转译
    String[] split2 = "a.ab.abc".split("\\.");
    System.out.println(Arrays.toString(split2));  // 结果为["a", "ab", "abc"]
    
    // | 需要转译
    String[] split3 = "a|ab|abc".split("\\|");
    System.out.println(Arrays.toString(split3));  // 结果为["a", "ab", "abc"]
  • 反例

    1
    2
    3
    4
    5
    6
    
    // String.split(String regex) 反例
    String[] split = "a.ab.abc".split(".");
    System.out.println(Arrays.toString(split));   // 结果为[]
    
    String[] split1 = "a|ab|abc".split("|");
    System.out.println(Arrays.toString(split1));  // 结果为["a", "|", "a", "b", "|", "a", "b", "c"]

枚举的属性字段必须是私有且不可变的

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public enum SwitchStatus {
    // 枚举的属性字段正例
    DISABLED(0, "禁用"),
    ENABLED(1, "启用");

    // final 修饰
    private final int value;
    private final String description;

    private SwitchStatus(int value, String description) {
        this.value = value;
        this.description = description;
    }

    // 没有Setter 方法
    public int getValue() {
        return value;
    }

    public String getDescription() {
        return description;
    }
}

MyBatis多条件查询使用where表达式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<select id="queryBookInfo" parameterType="com.tjt.platform.entity.BookInfo" resultType="java.lang.Integer">
 select count(*) from t_rule_BookInfo t
<where>
<if test="title !=null and title !='' ">
 title = #{title}
</if>
<if test="author !=null and author !='' ">
 AND author = #{author}
</if>
</where>
</select>