title: array of type T (Java generics)
body: <p>Although this code compiles successfully, it throws a class cast exception error at run-time:</p>
  
  <pre><code>class Test {
      public static void main(String[] args) {
          MyArray&lt;String&gt; x = new MyArray&lt;&gt;();
          x.a[0] = "test string";
      }
  }
  
  class MyArray&lt;T&gt; {
      T[] a;
  
      MyArray() {
          this.a = (T[]) new Object[1];
      }
  }
  </code></pre>
  
  <p>The error message:</p>
  
  <pre><code>Exception in thread "main" java.lang.ClassCastException:
  [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
      at Test.main(Test.java:4)
  </code></pre>
  
  <p>One possible, yet simple, solution I know of is to declare the array as an array of type <em>Object</em> and then just cast an array element back to T when you want to retrieve it from the array, like this:</p>
  
  <pre><code>class Test {
      public static void main(String[] args) {
          MyArray&lt;String&gt; x = new MyArray&lt;&gt;();
          x.a[0] = "test string";
          System.out.println(x.get(0));
      }
  }
  
  class MyArray&lt;T&gt; {
      Object[] a;
  
      MyArray() {
          this.a = new Object[1];
      }
  
      T get(int index) {
          return (T) a[index];
      }
  }
  </code></pre>
  
  <p>This works just fine. But the problem with this approach though is that I can now put absolutely anything in the array and yet keep it there safe and sound until such time as I try to pull it out of the array which will give me a big, fat class cast exception error!</p>
  
  <pre><code>    MyArray&lt;String&gt; x = new MyArray&lt;&gt;();
      x.a[0] = 34;
      System.out.println(x.get(0)); // run-time error
  </code></pre>
  
  <p>This is what we'd get if we ran this piece of code:</p>
  
  <pre><code> Exception in thread "main" java.lang.ClassCastException: 
   java.lang.Integer cannot be cast to java.lang.String
      at Test.main(Test.java:5)
  </code></pre>
  
  <p>Obviously, it's a lot better when all your array elements are of the same type as opposed to being generic objects of type <em>Object</em>. There's gotta be a way to do that.</p>
  
  <p>By the way, the example code I presented here has been significantly simplified. I know that I can use set and get methods that can do the necessary type casting which, of course, will help make it completely safe to add and get elements in and out of the array. The problem with this is that if I have lots of other methods in the class that also do a lot of casting, the tedium of writing all those cast operators becomes a real pain. I thought it'd be really nice if I could just store all the elements in the array as a certain type from the word go. This would simplify the coding process and make code much cleaner and easier to read. So, any words of wisdom you wanna pass my way are most welcome and going to be much appreciated.</p>