Although this code compiles successfully, it throws a class cast exception error at run-time:
class Test {
public static void main(String[] args) {
MyArray<String> x = new MyArray<>();
x.a[0] = "test string";
}
}
class MyArray<T> {
T[] a;
MyArray() {
this.a = (T[]) new Object[1];
}
}
The error message:
Exception in thread "main" java.lang.ClassCastException:
[Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
at Test.main(Test.java:4)
One possible, yet simple, solution I know of is to declare the array as an array of type Object and then just cast an array element back to T when you want to retrieve it from the array, like this:
class Test {
public static void main(String[] args) {
MyArray<String> x = new MyArray<>();
x.a[0] = "test string";
System.out.println(x.get(0));
}
}
class MyArray<T> {
Object[] a;
MyArray() {
this.a = new Object[1];
}
T get(int index) {
return (T) a[index];
}
}
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!
MyArray<String> x = new MyArray<>();
x.a[0] = 34;
System.out.println(x.get(0)); // run-time error
This is what we'd get if we ran this piece of code:
Exception in thread "main" java.lang.ClassCastException:
java.lang.Integer cannot be cast to java.lang.String
at Test.main(Test.java:5)
Obviously, it's a lot better when all your array elements are of the same type as opposed to being generic objects of type Object. There's gotta be a way to do that.
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.