Standardization write Java code

Standardization write Java code

A, iteration entrySet () Retrieves the Map of the key and value

When the loop only needs to acquire Map primary key key, iteration keySet () is correct; however, when you need a primary key key and value value, iteration entrySet () is a more efficient approach, which keySet than the first iteration () by then go get the value of better performance.

//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);
}

Second, the use Collection.isEmpty () detects an empty

Use of a Collection, () is empty is not detected on the logical problems, but using Collection.isEmpty () makes the code more readable, better performance can be obtained; in addition, any Collection.isEmpty () implemented time complexity is O (1), multiple cycles need not traverse, but by a certain time complexity of a Collection, () method implementation may be 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.");
}

Third, To recall Collection.contains method frequently use the Set

In the Java collection class library, List contains the general method of time complexity of O (n), if the code contains method calls frequently find the first set of data is converted into a list HashSet achieved, the O (n) time complexity will be 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);
}

The use of static code block implements static member variable assignment

For static member variables collection types, you should use static code block assignment, instead of using a set of implementation to assignment

//赋值静态成员变量正例
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");
    }
};

V. tools shield constructor

Tools is a collection of a bunch of static fields and functions, which should not be instantiated; however, Java adds an implicit public constructor for each class is not explicitly defined constructor, in order to avoid unnecessary instantiation, should explicit definition of private constructors to shield the implicit public constructor.

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 {
   

Sixth, the string conversion using String.valueOf (value) instead of "" + value

When the type or other objects into a string, using String.valueOf (value) "" + is higher than the efficiency value.

//把其它对象或类型转化为字符串正例:
int num = 520;
// String.valueOf() 效率更高
String strLove = String.valueOf(num);
//把其它对象或类型转化为字符串反例:
int num = 520;
// "" + value
String strLove = "" + num;

Seven, avoid using BigDecimal (double)

BigDecimal (double) the presence of risk of loss of precision, the exact calculation of the comparison values ​​or the scene may cause the business logic exception.

// BigDecimal 正例
BigDecimal bigDecimal1 = bigDecimal.valueOf(0.11D);

// BigDecimal 反例    
BigDecimal bigDecimal = new BigDecimal(0.11D);

Eight, returns an empty array rather than null and collections

If the program run returns null, null square mandatory testing needs to be called, otherwise it will throw null pointer exception; returns an empty array or an empty set, effectively avoid the situation because the caller does not detect null null pointer exception is thrown, you can also delete the caller detect null statement makes the code more concise.

//返回空数组和空集正例
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;
}

Nine, the priority value equals method call using constant or determined

equals method as easily shorting pointer exception, should be used with a constant value or determined object to call the equals method.

//调用 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");
}

Ten, enumeration of attribute fields must be private and immutable

Enumeration is generally used as a constant, or if the common attribute field setting field enumeration methods exist, then the enumeration constant properties can easily be modified; ideally, enumeration property fields are private, proprietary and constructor, assignment, there is no corresponding method Setter, preferably together with the final modifier.




正例:

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;
    }
}

remove / add operations not carried out in the elements in the foreach loop

If you want to remove operation, you can call the remove method of the iterator class rather than remove method of collection. If you modify the list because after the iterator is created from the structure at any time, in any way except through the iterator's own remove / add methods, the iterator will throw a ConcurrentModificationException, which is fail-fast mechanism produced by a single thread state.

fail-fast 机制 :多个线程对 fail-fast 集合进行修改的时,可能会抛出ConcurrentModificationException,单线程下也会出现这种情况,上面已经提到过。

java.util package following set of all classes are fail-fast, and java.util.concurrent package below all the classes are 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);
	}
}
Published 30 original articles · won praise 8 · views 20000 +

Guess you like

Origin blog.csdn.net/wg22222222/article/details/103936039
Recommended