ClassCast Exception in java, cannot cast to Ljava.lang.Integer
<p>I am trying to use java generics-</p>

<pre><code> public T[] toArray()
   {


      T[] result = (T[])new Object[numberOfEntries]; 

       // some code here to fill the resultarray



     return result;
   } // end toArray
</code></pre>

<p>Now in my main funciton, this is what I am doing-</p>

<pre><code>        A&lt;Integer&gt; obj= new A&lt;Integer&gt; ();

        obj.add(1); //add method not shown here as it is not relevant to question
        obj.add(2);
        obj.add(3);
        obj.add(4);


        Integer arr[] = (Integer[]) obj.toArray();
</code></pre>

<p>I get the following error-</p>

<pre><code>Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;
    at tester.main(tester.java:14)
</code></pre>

<p>How can I fix this?</p>