判断lis是否为空。用list.size()== 0,还是用list.isEmpty(),或者是null == list

首先我们先看List<>的部分源码,通过注释我们可以理解isEmpty()方法是判断list中有没有元素,list.size()判断list中元素的个数。

所以list.isEmpty 和list.size()==0意思是相同的。

 /**
     * Returns the number of elements in this list.  If this list contains
     * more than <tt>Integer.MAX_VALUE</tt> elements, returns
     * <tt>Integer.MAX_VALUE</tt>.
     *
     * @return the number of elements in this list
     */
    int size();

    /**
     * Returns <tt>true</tt> if this list contains no elements.
     *
     * @return <tt>true</tt> if this list contains no elements
     */
    boolean isEmpty();

而null == list 是判断对象是否存在。所以要先判断list对象是否存在,这样才能避免NullPointException,然后再去判断对象中是否有元素。

        @Autowired
	private static LogisticInfoService logisticInfoService;
	public static void main(String[] args) {
		
		 List<Map<String,Object>> list = logisticInfoService.queryOrderNo();
		 System.out.println(list);
	}

当数据库查到的数据为null时,就会报空指针异常。为什么会报空指针异常,list连地址都没有,肯定会报空指针异常。有地址,指针才有用武之地。

猜你喜欢

转载自blog.csdn.net/txhljjb/article/details/88313871