规范化编写Java代码
一、迭代entrySet() 获取Map 的key 和value
当循环中只需要获取Map 的主键key时,迭代keySet() 是正确的;但是,当需要主键key 和取值value 时,迭代entrySet() 才是更高效的做法,其比先迭代keySet() 后再去通过get 取值性能更佳。
//Map 获取key & value 正例:
HashMap<String, String> map = new HashMap<>();
for (Map.Entry<String,String> entry : map.entrySet()){
String key = entry.getKey();
String value = entry.getValue();
}
//Map 获取value 反例:
HashMap<String, String> map = new HashMap<>();
for (String key : map.keySet()){
String value = map.get(key);
}
二、使用Collection.isEmpty() 检测空
使用Collection.size() 来检测是否为空在逻辑上没有问题,但是使用Collection.isEmpty() 使得代码更易读,并且可以获得更好的性能;除此之外,任何Collection.isEmpty() 实现的时间复杂度都是O(1) ,不需要多次循环遍历,但是某些通过Collection.size() 方法实现的时间复杂度可能是O(n)
//正例:
LinkedList<Object> collection = new LinkedList<>();
if (collection.isEmpty()){
System.out.println("collection is empty.");
}
//检测是否为null 可以使用CollectionUtils.isEmpty()
if (CollectionUtils.isEmpty(collection)){
System.out.println("collection is null.");
}
//反例
LinkedList<Object> collection = new LinkedList<>();
if (collection.size() == 0){
System.out.println("collection is empty.");
}
三、若需频繁调用Collection.contains 方法则使用Set
在Java 集合类库中,List的contains 方法普遍时间复杂度为O(n),若代码中需要频繁调用contains 方法查找数据则先将集合list 转换成HashSet 实现,将O(n) 的时间复杂度将为O(1)。
//频繁调用Collection.contains() 正例
List<Object> list = new ArrayList<>();
Set<Object> set = new HashSet<>();
for (int i = 0; i <= Integer.MAX_VALUE; i++){
//时间复杂度为O(1)
if (set.contains(i)){
System.out.println("list contains "+ i);
}
}
//频繁调用Collection.contains() 反例
List<Object> list = new ArrayList<>();
for (int i = 0; i <= Integer.MAX_VALUE; i++){
//时间复杂度为O(n)
if (list.contains(i))
System.out.println("list contains "+ i);
}
四、使用静态代码块实现赋值静态成员变量
对于集合类型的静态成员变量,应该使用静态代码块赋值,而不是使用集合实现来赋值
//赋值静态成员变量正例
private static Map<String, Integer> map = new HashMap<String, Integer>();
static {
map.put("Leo",1);
map.put("Family-loving",2);
map.put("Cold on the out side passionate on the inside",3);
}
private static List<String> list = new ArrayList<>();
static {
list.add("Sagittarius");
list.add("Charming");
list.add("Perfectionist");
}
//赋值静态成员变量反例
private static Map<String, Integer> map = new HashMap<String, Integer>(){
{
map.put("Leo",1);
map.put("Family-loving",2);
map.put("Cold on the out side passionate on the inside",3);
}
};
private static List<String> list = new ArrayList<>(){
{
list.add("Sagittarius");
list.add("Charming");
list.add("Perfectionist");
}
};
五、工具类中屏蔽构造函数
工具类是一堆静态字段和函数的集合,其不应该被实例化;但是,Java 为每个没有明确定义构造函数的类添加了一个隐式公有构造函数,为了避免不必要的实例化,应该显式定义私有构造函数来屏蔽这个隐式公有构造函数。
public class PasswordUtils {
//工具类构造函数正例
private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class);
//定义私有构造函数来屏蔽这个隐式公有构造函数
private PasswordUtils(){}
public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";
public static String encryptPassword(String aPassword) throws IOException {
return new PasswordUtils(aPassword).encrypt();
}
public class PasswordUtils {
//工具类构造函数反例
private static final Logger LOG = LoggerFactory.getLogger(PasswordUtils.class);
public static final String DEFAULT_CRYPT_ALGO = "PBEWithMD5AndDES";
public static String encryptPassword(String aPassword) throws IOException {
六、字符串转化使用String.valueOf(value) 代替 " " + value
把其它对象或类型转化为字符串时,使用String.valueOf(value) 比 “”+value 的效率更高。
//把其它对象或类型转化为字符串正例:
int num = 520;
// String.valueOf() 效率更高
String strLove = String.valueOf(num);
//把其它对象或类型转化为字符串反例:
int num = 520;
// "" + value
String strLove = "" + num;
七、避免使用BigDecimal(double)
BigDecimal(double) 存在精度损失风险,在精确计算或值比较的场景中可能会导致业务逻辑异常。
// BigDecimal 正例
BigDecimal bigDecimal1 = bigDecimal.valueOf(0.11D);
// BigDecimal 反例
BigDecimal bigDecimal = new BigDecimal(0.11D);
八、返回空数组和集合而非 null
若程序运行返回null,需要调用方强制检测null,否则就会抛出空指针异常;返回空数组或空集合,有效地避免了调用方因为未检测null 而抛出空指针异常的情况,还可以删除调用方检测null 的语句使代码更简洁。
//返回空数组和空集正例
public static Result[] getResults() {
return new Result[0];
}
public static List<Result> getResultList() {
return Collections.emptyList();
}
public static Map<String, Result> getResultMap() {
return Collections.emptyMap();
}
//返回null 反例
public static Result[] getResults() {
return null;
}
public static List<Result> getResultList() {
return null;
}
public static Map<String, Result> getResultMap() {
return null;
}
九、优先使用常量或确定值调用equals 方法
象的equals 方法容易抛空指针异常,应使用常量或确定有值的对象来调用equals 方法。
//调用 equals 方法正例
private static boolean fileReader(String fileName)throws IOException{
// 使用常量或确定有值的对象来调用 equals 方法
return "Charming".equals(fileName);
//或使用:java.util.Objects.equals() 方法
return Objects.equals("Charming",fileName);
}
//调用 equals 方法反例
private static boolean fileReader(String fileName)throws IOException{
// 可能抛空指针异常
return fileName.equals("Charming");
}
十、枚举的属性字段必须是私有且不可变
枚举通常被当做常量使用,如果枚举中存在公共属性字段或设置字段方法,那么这些枚举常量的属性很容易被修改;理想情况下,枚举中的属性字段是私有的,并在私有构造函数中赋值,没有对应的Setter 方法,最好加上final 修饰符。
正例:
public enum SwitchStatus {
// 枚举的属性字段正例
DISABLED(0, "禁用"),
ENABLED(1, "启用");
// final 修饰
private final int value;
private final String description;
private SwitchStatus(int value, String description) {
this.value = value;
this.description = description;
}
// 没有Setter 方法
public int getValue() {
return value;
}
public String getDescription() {
return description;
}
}
public enum SwitchStatus {
// 枚举的属性字段反例
DISABLED(0, "禁用"),
ENABLED(1, "启用");
public int value;
private String description;
private SwitchStatus(int value, String description) {
this.value = value;
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
不要在 foreach 循环里进行元素的 remove/add 操作
如果要进行remove操作,可以调用迭代器的 remove方法而不是集合类的 remove 方法。因为如果列表在任何时间从结构上修改创建迭代器之后,以任何方式除非通过迭代器自身remove/add方法,迭代器都将抛出一个ConcurrentModificationException,这就是单线程状态下产生的 fail-fast 机制。
fail-fast 机制 :多个线程对 fail-fast 集合进行修改的时,可能会抛出ConcurrentModificationException,单线程下也会出现这种情况,上面已经提到过。
java.util包下面的所有的集合类都是fail-fast的,而java.util.concurrent包下面的所有的类都是fail-safe的。
//强制,不要在foreach循环里进行元素的remove/add操作。remove元素需要使用Iterator方式,如果并发操作,需要对Iterator对象加锁。
//正例
List<String> list = new ArrayList<>();
list.add("1");
list.add("2");
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
String item = iterator.next();
if(删除元素的条件){
iterator.remove();
}
}
//反例
for(String item : list){
if("1".equals(item)){
list.remove(item);
}
}