超级棒的代码

在阅读源码的过程中,记录一些超级棒的写法。

判断 null

requireNonNull 方法的使用

1
Objects.requireNonNull(metric, "metric missing");

底层实现

1
2
3
4
5
public static <T> T requireNonNull(T obj, String message) {
if (obj == null)
throw new NullPointerException(message);
return obj;
}

判断相等

这样就不用在意 equals 方法的空指针异常了

1
Objects.equals("keywords", sortMetric)

底层

1
2
3
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}

String.join

https://www.hexianwei.com/2019/06/20/StringJoiner/

1
2
3
4
5
6
7
8
9
10
public static String join(CharSequence delimiter, CharSequence... elements) {
Objects.requireNonNull(delimiter);
Objects.requireNonNull(elements);
// Number of elements not likely worth Arrays.stream overhead.
StringJoiner joiner = new StringJoiner(delimiter);
for (CharSequence cs: elements) {
joiner.add(cs);
}
return joiner.toString();
}

模仿 String.join 实现一个 listJoin

1
2
3
4
5
6
7
8
9
public static String joinMethodThree(List<String> list, String delimiter) {
Objects.requireNonNull(delimiter);
Objects.requireNonNull(list);
StringJoiner joiner = new StringJoiner(delimiter);
for (CharSequence cs : list) {
joiner.add(cs);
}
return joiner.toString();
}
Look at your mood.