1、The diamond operator ("<>") should be used12
在定义集合的时候,等号右边的<>内不需要再写上元素类型,直接空着就行
Noncompliant Code Example:不规范的示例
List<String> strings = new ArrayList<String>(); // Noncompliant
Map<String, List<Integer>> map = new HashMap<String, List<Integer>>(); // Noncompliant
Compliant Solution :规范的示例
List<String> strings = new ArrayList<>();
Map<String, List<Integer>> map = new HashMap<>();
2、“switch” statements should end with a “default” clause4
switch语句应该以default结束,这是一种defensive programming思想
3、Primitives should not be boxed just for “String” conversion2
不要使用 4+" "这样的方式将int值转变为字符串,而是使用 Integer.toString(4)这样的方式。
就像Integer.parseInt(“我是字符串”)这样,不要偷懒。
4、“entrySet()” should be iterated when both the key and value are needed2
直接看英文更直接:When only the keys from a map are needed in a loop, iterating the keySet makes sense. But when both the key and the value are needed, it’s more efficient to iterate theentrySet, which will give access to both the key and value, instead.
也就是说,如果只需要Map的Key,那么直接iterate这个Map的keySet就可以了,但是如果Key和value都需要,就iterate这个Map。具体看下面的19.
5、Collection.isEmpty() should be used to test for emptiness2
当判断集合是否为空的时候,不要使用if (myCollection.size() == 0) 这样的方式,而是使用if (myCollection.isEmpty()这样的方式,后者性能更高。
6、Synchronized classes Vector, Hashtable, Stack and StringBuffer should not be used1
不要使用同步的Vector/HashTable/Stack/StringBuffer等。在早期,出于线程安全问题考虑,java API 提供了这些类。但是同步会极大影响性能,即使是在同一个线程中使用他们。
通常可以这样取代:
ArrayList or LinkedList instead of Vector
Deque instead of Stack
HashMap instead of Hashtable
StringBuilder instead of StringBuffer
Exit methods should not be called
尽量不要调用system.exit()方法。
7、Local Variables should not be declared and then immediately returned or thrown7
本地变量如果赋值之后直接return了,那就直接return本地变量的赋值语句。
8、String literals should not be duplicated5
字符串不应该重复,如果多次用到同一字符串,建议将该字符串定义为字符串常量,再引用
9、Magic numbers should not be used
float radius=3.0f // 定义半径为3.0
float perimeter=radus*3.14 // 周长为半径*3.14
没有特定说明,3.14这个数就用的很魔幻,导致代码可读性差,修改不方便的问题。
正确的做法是不要在代码中直接用特定的数值,而应该将其定义为常量、枚举类型或者是宏定义(C、C++或者objective -c)
10、Modifiers should be declared in the correct order2
修饰符等要按约定俗成的顺序书写 ,例如,写成public static final 而不是static public final