java

Map
  1. 当循环中只需要 Map 的主键时,迭代 keySet() 是正确的。但是,当需要主键和取值时,迭代 entrySet() 才是更高效的做法,比先迭代 keySet() 后再去 get 取值性能更佳
 HashMap<String, String> map = new HashMap<>();
       map.put("name", "lhh");
       map.put("tel", "15717085241");
       System.out.println(map.values());
       for (Map.Entry<String, String> entry : map.entrySet()) {
           System.out.println(entry.getKey() + "\t"  + entry.getValue());
       }
Collection
  1. 使用Conllection.isEmpty 判断是否有内容,而不是Conllection.size()
 Collection<Object> collection = new ArrayList<>();
 System.out.println(collection.isEmpty() ? "空" : collection.size());
  1. 如果需要还需要检测 null ,可采用:
    • CollectionUtils.isEmpty(collection)
    • CollectionUtils.isNotEmpty(collection)
Collection<Object> collection0 = null;
System.out.println(CollectionUtils.isEmpty(collection0));
System.out.println(CollectionUtils.isNotEmpty(collection0));
  1. 尽量在集合初始化时指定集合的大小和泛型
Collection<String> collection = new ArrayList<>(initialCapacity);
  1. 频繁调用 Collection.contains 方法请使用 Set
Set<Object> set = new HashSet<Object>(collection);
set.contains(key);

String

  1. 字符串拼接使用 StringBuilder
// 經測試,使用String拼接1-10000 用時1909ms ,StringBuilder用時10ms 
// 其中使用到了字符串打印,可能時間會有些出入,但用來比較兩個時間差度已足夠
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 1000; i++) {
    stringBuilder.append(i);
}
System.out.println(stringBuilder);
  1. 使用 String.valueOf(value) 代替 ""+value
int value = 99999;
String stringValue = String.valueOf(value);

Other

  1. 不要輕易使用魔法值

  2. 工具类应该屏蔽构造函数

  3. 过时代码添加 @Deprecated 注解

  4. 优先使用常量或确定值来调用 equals 方法

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。