title: java 6 ArrayLists and Arrays and Generics
body: <p>I have a varargs method and I want to call the method using 1 or 0 arguments.
  The following code compiles, but does not run correctly:</p>
  
  <pre><code>final List&lt;MyMessage&gt; allMessages = new ArrayList&lt;MyMessage&gt;();
  MyMessage message = null;
  if (checkSomeCondition()) {
    message = new MyMessage(someParam);
    allMessages.add(message);
  }
  
  int size = allMessages.size();
  MyMessage[] msgArrayType = new MyMessage[size]; // ERROR
  MyMessage[] msgArray = allMessages.toArray(msgArrayType);
  
  callFunc(msgArray);
  ...........
  public void callFunc(MyMessage... messages) {
  
  }
  </code></pre>
  
  <p>When I debug the code, after the line that I marked with <code>//ERROR</code>, the value of the array <code>msgArrayType</code> is <code>com.sun.jdi.ClassNotLoadedException: Type has not been loaded occurred while retrieving component type of array.</code></p>
  
  <p>This is also wrong:</p>
  
  <pre><code>MyMessage[] msgArray = (MyMessage[]) allMessages.toArray();
  // -&gt; java.lang.Object cannot be cast to .......MyMessage
  </code></pre>
  
  <p>I really don't understand it, because <code>allMessages</code> is a <code>List</code> of <code>MyMessage</code>s!</p>
  
  <p>The only option I see is to use something like</p>
  
  <pre><code>if (message == null) {
    callFunc();
  } else {
    callFunc(message);
  }
  </code></pre>
  
  <p>but I was wondering how the code would look like if I want to write <code>callFunc</code> only once. Any suggestions?</p>