推荐使用JDK7中新引入的Objects工具类来进行对象的equals比较,直接a.equals(b),有空指针异常的风险
public final class Objects {/** * Returns {@code true} if the arguments are equal to each other * and {@code false} otherwise. * Consequently, if both arguments are {@code null}, {@code true} * is returned and if exactly one argument is {@code null}, {@code * false} is returned. Otherwise, equality is determined by using * the {@link Object#equals equals} method of the first * argument. * * @param a an object * @param b an object to be compared with {@code a} for equality * @return {@code true} if the arguments are equal to each other * and {@code false} otherwise * @see Object#equals(Object) */ public static boolean equals(Object a, Object b) { return (a == b) || (a != null && a.equals(b)); } }
示例:如下所示,如果需要进行equals的两个都是字符串变量,那么就应该使用Objects.equals(Object a,Object b) 方法。
for(int k = 0; k < listSize; k ++){ Map<String,Object> item = list.get(k); String curInStoreNoteNo = item.get("inStoreNoteNo").toString(); String curDeliveryEntNo = item.get("deliveryEntNo").toString(); if(k > 0){ Map<String,Object> map = list.get(k - 1); String inStoreNoteNo = map.get("inStoreNoteNo").toString(); String deliveryEntNo = map.get("deliveryEntNo").toString(); if(curInStoreNoteNo.equals(inStoreNoteNo) && curDeliveryEntNo.equals(deliveryEntNo)){ if(k == listSize - 1){ margeRowList.add(k); } }else{ margeRowList.add(k-1); } } ... }
修改如下:
for(int k = 0; k < listSize; k ++){ Map<String,Object> item = list.get(k); String curInStoreNoteNo = item.get("inStoreNoteNo").toString(); String curDeliveryEntNo = item.get("deliveryEntNo").toString(); if(k > 0){ Map<String,Object> map = list.get(k - 1); String inStoreNoteNo = map.get("inStoreNoteNo").toString(); String deliveryEntNo = map.get("deliveryEntNo").toString(); if(Objects.equals(curInStoreNoteNo,inStoreNoteNo) && Objects.equals(curDeliveryEntNo,deliveryEntNo)){ if(k == listSize - 1){ margeRowList.add(k); } }else{ margeRowList.add(k-1); } } .... }