0

I want to use a class to create an array of Objects and then cast this array to its type without casting every individual Object inside of it, is this possible?

This is what i tried so far:

class Bar {
    public void hello() {
        System.out.println("Hello from inside of bar");
    }
}

using a class to create an Object array:

class Arr<T> {

    Object[] obj;
    int i = 0;

    public Arr(int size) {
        obj = new Object[size];
    }

    public void add(T t) {
        obj[i] = t;
        i++;
    }
}

second try, defining array with T instead of Object:

class ArrTwo<T> {

    T[] obj;
    int i = 0;

    public ArrTwo(int size) {
        obj = (T[]) new Object[size];
    }

    public void add(T t) {
        obj[i] = t;
        i++;
    }
}

and the Main:

class Main {

    public static void main(String args[]) {
        TestArr();
        TestArrTwo();
    }

    public static void TestArr() {
        Arr<Bar> arr = new Arr<Bar>(1);
        arr.add(new Bar());
        Bar barArr[] = (Bar[]) arr.obj; // java.lang.ClassCastException
        barArr[0].hello();
    }

    public static void TestArrTwo() {
        ArrTwo<Bar> arr = new ArrTwo<Bar>(1);
        arr.add(new Bar());
        Bar barArr[] = (Bar[]) arr.obj;  // java.lang.ClassCastException
        barArr[0].hello();
    }
}

Both testing functions give me this error:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LBar;
pppery
  • 3,434
  • 13
  • 24
  • 37
Alexanus
  • 605
  • 4
  • 18

0 Answers0