zoukankan      html  css  js  c++  java
  • JAVA代码优化

    JAVA基础

    数字类转换

    禁止使用构造方法 BigDecimal(double)


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

    BigDecimal value = new BigDecimal(0.1D); // 0.100000000000000005551115...


    正例:

    BigDecimal value = BigDecimal.valueOf(0.1D);; // 0.1

    使用String.valueOf(value)代替""+value


    当要把其它对象或类型转化为字符串时,使用 String.valueOf(value) 比""+value 的效率更高。

    反例:
    int i = 1;
    String s = "" + i;

    正例:
    int i = 1;
    String s = String.valueOf(i);
     

    集合类

    频繁调用 Collection.contains 方法请使用 Set


    在 java 集合类库中,List 的 contains 方法普遍时间复杂度是 O(n) ,如果在代码中需要频繁调用 contains 方法查找数据,可以先将 list 转换成 HashSet 实现,将 O(n) 的时间复杂度降为 O(1) 。
    反例:
    ArrayList<Integer> list = otherService.getList();
    for (int i = 0; i <= Integer.MAX_VALUE; i++) {
    // 时间复杂度O(n)
    list.contains(i);
    }

    正例:
    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);
    }

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

    final修饰

    小心String.split(String regex)
    字符串 String 的 split 方法,传入的分隔字符串是正则表达式!部分关键字(比如.[]()| 等)需要转义
    反例:

    "a.ab.abc".split("."); // 结果为[]
    "a|ab|abc".split("|"); // 结果为["a", "|", "a", "b", "|", "a", "b", "c"]

    正例:

    "a.ab.abc".split("\."); // 结果为["a", "ab", "abc"]
    "a|ab|abc".split("\|"); // 结果为["a", "ab", "abc"]

    建议使用 try-with-resources 语句


    Java 7 中引入了 try-with-resources 语句,该语句能保证将相关资源关闭,优于原来的 try-catch-finally 语句,并且使程序代码更安全更简洁。
    反例:
    private void handle(String fileName) {
    BufferedReader reader = null;
    try {
    String line;
    reader = new BufferedReader(new FileReader(fileName));
    while ((line = reader.readLine()) != null) {
    ...
    }
    } catch (Exception e) {
    ...
    } finally {
    if (reader != null) {
    try {
    reader.close();
    } catch (IOException e) {
    ...
    }
    }
    }
    }

    正例:
    private void handle(String fileName) {
    try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
    String line;
    while ((line = reader.readLine()) != null) {
    ...
    }
    } catch (Exception e) {
    ...
    }
    }
     
  • 相关阅读:
    js 控制页面跳转的5种方法
    弹性盒
    js中变量声明有var和没有var的区别
    解决Cannot read property 'style' of null中样式问题
    JS中用for循环解决重复定义的问题
    博客第一天
    jQuery 无缝轮播
    随鼠标移动
    倒计时
    轮播图
  • 原文地址:https://www.cnblogs.com/anhaogoon/p/12216825.html
Copyright © 2011-2022 走看看