正在将数组初始化为null,但null比较失败



在下面的代码中,我的期望是如果列表readerList.size = 0headerLine应该是方法commonValidation()中的null。但事实并非如此,有人能告诉我为什么吗?

String[] headerLine = null;
if (readerList != null && readerList.size() != 0){
    headerLine = readerList.get(0);         
}
commonValidation(headerLine, logDTO, hrGroupName, feedFileName);

//方法定义

public void commonValidation(String[] headerLine, TransactionLogDTO logDTO, String hrGroupName, String filename) throws PersistenceException, ServiceException, Exception {
    if ((headerLine == null) || (headerLine.length == 0)){
        logDTO.setGyr("R");
            String subject = MessageWrapper.getMessage("hr.mail.emptyfile.subject");
        String body = MessageWrapper.getMessage("hr.mail.emptyfile.body", filename);
            if (logDTO.getMessage() == null){
                logDTO.setMessage(body);
            }
            else{
                logDTO.setMessage(logDTO.getMessage() + ";" + body);
            }
        logDTO.setIsLogErrorMailSent(Boolean.TRUE);
        sendTransactionLogErrorReport(hrGroupName, subject, body);                  
        throw new Exception(body);
    }
}

String[] headerLine = null;这是成员变量吗?如果是,则使其成为方法局部变量。

还有

您可以在ArrayList中添加null元素,并且大小会增加。

    ArrayList<String[]> arrayList = new ArrayList<String[]>();
    arrayList.add(null);
    System.out.println(arrayList.size());

将打印1而不是0

因此检查readerList.get(0)是否为null

以下是ArrayList add方法的源代码

 410       public boolean add(E e) {
 411           ensureCapacityInternal(size + 1);  // Increments modCount!!
 412           elementData[size++] = e;
 413           return true;
 414       }

如果您看到没有检查null,那么您将不得不自己进行检查:)

但事实并非如此,(…)

我不相信。如果readerList.size() == 0headerLine不更改值,则保持null

最新更新