title: Checking if a HashMap is empty without causing NullPointerException / IndexOutOfBoundsException?
body: <p>So am doing a mail server kind of program for my java course, (I would call myself a beginner in Java) and while I have completed all the required parts, there are some problems with the program that while the assignment doesn't require it, I would like to know why this is behaving the way and how to fix it. So to summarize it I have two methods that check how many mail items a specific user has and another one that returns the mail item that is first in the users mailbox, (by LIFO rule).</p>
  
  <p>So while if a user both A.Has a mailbox and B.Has at least 1 mail in said mailbox there isn't a problem, this doesn't really work when a and/or b isn't true. And that is what I tried to fix. I thought it would be as simple as checking both if the mailbox.containsKey(who)==false and/or mailbox.get(who).get(0) == null would be enough but when I do this i get java.lang.IndexOutOfBoundsException: Index: 0, Size: 0. </p>
  
  <p>I've tried multiple types of either checking if it's ==true/false null etc.. I've tried to just throw the exception all together but nothing seems to work and while maybe throwing the exception could work in some way I would want to solve it in another way as the throw command seems a bit lazy</p>
  
  <p>Here is my method in which I check both A and B:</p>
  
  <pre class="lang-java prettyprint-override"><code>private boolean errorHandling(String who){  
      if (mailbox.containsKey(who)==false ||  mailbox.get(who).get(0) == null    ){ 
          return true;  
      }
      else{
          return false;
      }
  }
  </code></pre>
  
  <p>and this method is utilized by these two methods:</p>
  
  <pre><code>public MailItem getNextMailItem(String who)
  {
      if (!errorHandling(who) ){   
          MailItem item2 = mailbox.get(who).get(0);
          mailbox.get(who).remove(0);
          return item2;
      } else{
          System.out.println("that user dosent have a mailbox");
          return null;
      }
  }
  
  public int howManyMailItems(String who)
  {
      if (!errorHandling(who) ){  //To check if user has a mailbox
          return mailbox.get(who).size();
      }
      else{
          System.out.println("that user dosent have a mailbox");
          return 0;
      }
  }  
  </code></pre>
  
  <p>I am not sure if you need more of my code to help me or not. Tell me if that is the case but to clarify, the "mailbox" is the hashmap and the who parameter is the person you want to check his or her mailbox. Thank you.</p>