版权声明:本文为CSDN博主「CSDN资讯」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/csdnnews/article/details/100987866
1. 循环中只需要Map的主键时, 迭代keySet(), 但是当需要主键和取值时,迭代entrySet()才是更高效的做法
反例:
Map<String, String> map = ...;
for(String key : map.keySet()){
String value = map.get(key);
...
}
正例:
Map<String, String> map = ...;
for(map.Entry<String, String> entry : map.entrySet()){
String key = entry.getKey();
String value = entry.getValue();
...
}
2. 应该使用Collection.isEmpty()检测空
使用Collection.size()来检测空逻辑上没有问题, 但是任何Collection.isEmpty()实现的时间复杂度都是O(1), 某些Collection.size()实现的时间复杂度是O(n).
3. 不要把集合对象传给自己
//反例
List<String> list = ...;
if(list.containsAll(list))...
4. 集合初始化尽量指定大小,因为集合每次扩容的时间复杂度很有可能是O(n).
5. 字符串拼接使用StringBuilder. 一般字符串拼接在编译期Java会进行优化. 但在循环中字符串拼接, java编译器无法优化, 所以要
使用StringBuilder
6. List随机访问: 数组的随机访问效率更高. (判断数组的内部实现是链表还是数组 list instance RandomAccess)
7. 频繁调用Collection.contains 方法请使用set, List的contains方法普遍时间复杂度是O(n).
ArrayList<Integer> list = otherService.getList();
Set<Integer> set = new HashSet(list);
for (int i = 0; i <= Integer.MAX_VALUE; i++) {
// 时间复杂度O(1)
set.contains(i);
}
8. 对于集合类型的静态成员变量,不要使用集合来实现赋值, 应该使用静态代码块
反例:
private static Map<String, Integer> map = new HashMap<String, Integer>() {
{
put("a", 1);
put("b", 2);
}
};
private static List<String> list = new ArrayList<String>() {
{
add("a");
add("b");
}
};
正例:
private static Map<String, Integer> map = new HashMap<>();
static {
map.put("a", 1);
map.put("b", 2);
};
private static List<String> list = new ArrayList<>();
static {
list.add("a");
list.add("b");
};
9. 建议使用try-with-resources语句, 能够保证将相关资源关闭. 优于try-catch-finally
private void handle(String fileName) {
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
...
}
} catch (Exception e) {
...
}
}
10. 工具类应该屏蔽构造函数(显式定义私有构造函数)
11. 判断null对象[Objects.isNull("类对象")]
12. String.valueOf(value) 效率更高
13. 返回空数组和空集合而不是null
14. 枚举的属性字段必须是私有不可变
枚举通常被当做常量使用,如果枚举中存在公共属性字段或设置字段方法,那么这些枚举常量的属性很容易被修改.理想情况下,枚举中的属性字段是私有的,并在私有构造函数中赋值,没有对应的setter方法,最好加上final修饰符
15. String.split(String regx) 传入的分割字符串是正则表达式!部分关键字[比如. [] () \ |]需要转义