一、建议

推荐使用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));
    }
}

二、Objects工具类

Objects是一个工具类,提供了一些对象操作的通用方法。

public static boolean equals(Object o1,Object o2)

比较两个对象是否相等,可以传递null值,避免出现空指针异常

注意: a) 以后 还会碰到 Arrays, Collections, Objects 这样的 类, 它的方法都是静态的, 这样的类都是工具类, 不用new 对象, 可以直接 类名.方法名() 调用方法.

b)空指针异常, NullPointerException , 在java中,如果一个对象为 null, 并且还去调用了对象.方法, 那么就肯定会有 NullPointerException 异常出现.

三、示例

如下所示,如果需要进行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);
                }
            }
       ....
        }

 

posted on 2022-01-20 09:28  周文豪  阅读(769)  评论(1编辑  收藏  举报