正例:
- // 挪用别人的处事获取到list
- List<Integer> list = otherService.getList();
- if (list instanceof RandomAccess) {
- // 内部数组实现,可以随机遇见
- System.out.println(list.get(list.size() - 1));
- } else {
- // 内部也许是链表实现,随机遇收服从低
- }
频仍挪用 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);
- }
让代码更优雅
长整型常量后添加大写 L
在行使长整型常量值时,后头必要添加 L ,必需是大写的 L ,不能是小写的 l ,小写 l 轻易跟数字 1 夹杂而造成误解。
反例:
- long value = 1l;
- long max = Math.max(1L, 5);
正例:
- long value = 1L;
- long max = Math.max(1L, 5L);
不要行使邪术值
当你编写一段代码时,行使邪术值也许看起来很明晰,但在调试时它们却不显得那么明晰了。这就是为什么必要把邪术值界说为可读取常量的缘故起因。可是,-1、0 和 1不被视为邪术值。
反例:
- for (int i = 0; i < 100; i++){
- ...
- }
- if (a == 100) {
- ...
- }
正例:
- private static final int MAX_COUNT = 100;
- for (int i = 0; i < MAX_COUNT; i++){
- ...
- }
- if (count == MAX_COUNT) {
- ...
- }
不要行使荟萃实现来赋值静态成员变量
对付荟萃范例的静态成员变量,不要行使荟萃实现来赋值,应该行使静态代码块赋值。
反例:
- 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");
- };
提议行使 try-with-resources 语句
Java 7 中引入了 try-with-resources 语句,该语句能担保将相干资源封锁,优于原本的 try-catch-finally 语句,而且使措施代码更安详更简捷。 (编辑:湖南网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|