为什么队列中的元素是相同的

时间:2017-09-28 09:37:07

标签: java queue

在项目中我负责邮件发送功能,但在出现问题时使用队列。

private void createReportEmail()
{
    try
    {
        List<Map> list = emailMapper.getToAddress();
        System.out.println(list);
        MailSenderInfo mailSenderInfo = new MailSenderInfo();
        mailSenderInfo = CreateEmailService.sendReportMail(emailMapper);
        InternetAddress address = new InternetAddress();
        for (int i = 0; i < list.size(); i++)
        {
            if (list.get(i).get("address").toString() != null && list.get(i).get("address").toString() != "")
                address = new InternetAddress(list.get(i).get("address").toString());
            MailSenderInfo mailSenderInfo2 = new MailSenderInfo();
            mailSenderInfo2 = mailSenderInfo;
            mailSenderInfo2.setAddress(address);
            queue.offer(mailSenderInfo2);
        }
        for(int i =0;i<list.size();++i)
        {
            System.out.println(queue.poll().getAddress());
        }

    } catch (Exception e)
    {
        e.printStackTrace();
    }
}

现在我确定列表中的元素彼此不同,但是队列中存储的所有内容都是列表中最后一个元素的内容。我想知道为什么

2 个答案:

答案 0 :(得分:3)

您正在循环的每次迭代中创建一个新的MailSenderInfo实例,这是正确的事情,但是您将其替换为现有的MailSenderInfo实例(在循环之前创建 - MailSenderInfo mailSenderInfo = new MailSenderInfo();),因此您始终将相同的MailSenderInfo实例添加到队列中:

    for (int i = 0; i < list.size(); i++) { 
        ...
        MailSenderInfo mailSenderInfo2 = new MailSenderInfo();
        mailSenderInfo2 = mailSenderInfo; // remove this
        mailSenderInfo2.setAddress(address);
        queue.offer(mailSenderInfo2);
    }

答案 1 :(得分:0)

我建议使用if

StringUtils阻止另一项更改
if (StringUtils.isNotBlank(list.get(i).get("address").toString()))
      address = new InternetAddress(list.get(i).get("address").toString());
      MailSenderInfo mailSenderInfo2 = new MailSenderInfo();
      mailSenderInfo2.setAddress(address);
      queue.offer(mailSenderInfo2);

并删除第mailSenderInfo2 = mailSenderInfo;行。因为mailSenderInfo包含较旧的对象引用。