无法在Java中向LinkedHashMap添加元素

时间:2016-09-20 16:57:10

标签: java arrays arraylist hashmap

我正在使用JavaMail API阅读电子邮件,并将每条消息(以及发件人,发送日期等)添加到LinkedHashMap。接下来,我将LinkedHashMap添加到LinkedHashMaps的ArrayList中。然而,奇怪的是整个Hashmap被最后一个条目覆盖。

我有以下代码:

private ArrayList<LinkedHashMap<String, String>> readAllMsgsFromOutlook() throws FileNotFoundException, IOException, MessagingException
    {

        LinkedHashMap<String, String> msgsLinkedHashMap = new LinkedHashMap<String, String>();
        ArrayList<LinkedHashMap<String, String>> msgsLinkedHashMapAsArrayList = new ArrayList<LinkedHashMap<String, String>>();

        //String host = "smtp-mail.outlook.com";

        String emailID = ..getEmail();
        String password = ..getPassword();
        Properties props = new Properties();

        props.setProperty("mail.store.protocol", "imaps");


        try {
            Session session = Session.getInstance(props, null);

            Store store = session.getStore("imaps");
            store.connect("imap-mail.outlook.com", emailID, password);
            Folder inboxFolder = store.getFolder("INBOX");
            UIDFolder UID = (UIDFolder)inboxFolder;

            Message[] msgs = null;


            Flags seen = new Flags(Flags.Flag.SEEN);
            FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
            msgs = inboxFolder.search(unseenFlagTerm);  


            System.out.println("Number of New Emails in Inbox: " + msgs.length + "\n");



            String senderAsString = "";
            String sentDateAsString = "";
            String subjectAsString = "";
            String contentAsString = "";
            String UIDAsString = "";


            for (int msgCounter = 0; msgCounter < msgs.length; msgCounter++) 

            {

                System.out.println("Email #: " + (msgCounter + 1) + "\n");

                Message msg  = msgs[msgCounter];
                long UIDAsLong = UID.getUID(msg);

                Object content = msg.getContent();  


                if (content instanceof String)  
                {  
                    System.out.println("Email is instance of String: \n");


                    Address[] sender = msg.getFrom();



                    senderAsString = sender[0].toString();
                    System.out.println("SENDER: " + senderAsString);
                    sentDateAsString = msg.getSentDate().toString();
                    System.out.println("SENT_DATE: " + sentDateAsString);

                    subjectAsString = msg.getSubject().toString();
                    System.out.println("SUBJECT: " + subjectAsString);
                    contentAsString = (String)content; 
                    System.out.println("CONTENT: " + contentAsString);

                    UIDAsString = String.valueOf(UIDAsLong);

                    System.out.println("UID: " + UIDAsString);


                    System.out.println("\n");



                }  
                else if (content instanceof Multipart)  
                {  
                    System.out.println("Email is instance of Multipart");

                    Multipart mp = (Multipart)content;  
                    BodyPart bp = mp.getBodyPart(0);
                    Address[] sender = msg.getFrom();
                    sentDateAsString = msg.getSentDate().toString();
                    subjectAsString = msg.getSubject();
                    contentAsString = bp.getContent().toString();

                    senderAsString = sender[0].toString();
                    System.out.println("SENDER: " + senderAsString);


                    System.out.println("SENT DATE: " + sentDateAsString);


                    System.out.println("SUBJECT: " + subjectAsString);
                    System.out.println("CONTENT: " + contentAsString);
                    UIDAsString = String.valueOf(UIDAsLong);

                    System.out.println("UID: " + UIDAsString);

                    System.out.println("\n");


                }



                msgsLinkedHashMap.put("sender", senderAsString);
                msgsLinkedHashMap.put("sentDate", sentDateAsString);
                msgsLinkedHashMap.put("subject", subjectAsString);
                msgsLinkedHashMap.put("content", contentAsString);
                msgsLinkedHashMap.put("UID", UIDAsString);



                msgsLinkedHashMapAsArrayList.add(msgsLinkedHashMap);



        }



        } catch (Exception mex) {
            // TODO Auto-generated catch block
            mex.printStackTrace();
        }

此时添加的内容似乎是正确的。例如,如果我有24条消息,内容是&#34; msg1&#34;,&#34; msg2&#34;,&#34; msg3&#34;等等,然后这个系统打印出正确的内容。

然而,当我在以下结束括号后循环遍历HashMap时,我得到的是第24个元素。换句话说,系统将始终打印&#34; msg24&#34;甚至对于以下代码中列表中的前23个元素:

        for (int arrayListCounter = 0; arrayListCounter < msgsLinkedHashMapAsArrayList.size(); arrayListCounter++) {

            LinkedHashMap<String, String> singleHashmapInArrayList = msgsLinkedHashMapAsArrayList.get(arrayListCounter);

            String content = singleHashmapInArrayList.get("content");

            System.out.println(">>> " + arrayListCounter + " : " + content);

//由于某种原因,内容总是等于msg24而不是msg1,msg2,msg3等。似乎第24个元素正在替换所有以前的元素。但为什么?             }

        return msgsLinkedHashMapAsArrayList;

    }

我一直试图找出问题几个小时。

我做错了什么?

1 个答案:

答案 0 :(得分:2)

当你在循环外部分配msgsLinkedHashMap变量时,你总是编辑同一个对象并继续将它的实例添加到列表中。解决方案是移动

Map<String, String> msgsLinkedHashMap = new LinkedHashMap<String, String>();
在你的for循环中

,这样你就可以在每次迭代时创建Map的新实例。