Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        2年前关闭。
                                                                                            
                
        
在项目中,我负责邮件发送功能,但是在出现问题时使用队列。

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();
    }
}


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

最佳答案

您正在循环的每次迭代中创建一个新的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);
    }

09-11 20:31