0

I was trying to construct a simple list class using generics.
However, it throws classcastexception when I was trying to print out the value. Is there any problem when I declare and initialize generic array?

class vector<E> {
    static int MAX_LEN = 1234567;
    E[] data;
    int[] prv;
    int to;
    int size;

    vector() {
        data = (E[])new Object[MAX_LEN];
        prv = new int[MAX_LEN];
        to = -1;
        size = 0;

        for(int i = 0; i < MAX_LEN; ++i) {
            prv[i] = -1;
        }
    }

    void push_back(E e) {
        data[size] = e;
        prv[size] = to;
        to = size;
        ++size;
    }
}

public class Main {

    public static void main(String[] args) throws Exception {
        vector<Integer> v = new vector();
        v.push_back(1);
        v.push_back(2);
        v.push_back(3);
        v.push_back(4);
        v.push_back(5);

        for(int i = v.to; i != -1; i = v.prv[i]) {
            System.out.println(v.data[i]); //<- Exception here
        }
    }
}
Peter Hwang
  • 971
  • 1
  • 12
  • 25
  • Have you read [this](https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array) ? – cactuschibre Oct 26 '18 at 23:58
  • I checked your link and I do not think it is relevant since it throws exception instead of printing the address of the object. – Peter Hwang Oct 27 '18 at 00:03
  • But strangely enough, I got right result after adding a simple getter method on the class. Still confused. – Peter Hwang Oct 27 '18 at 00:03

2 Answers2

1

There are a few things wrong with the code.

  1. It looks like, you've missed a <> in the line vector<Integer> v = new vector();
  2. A cast from Object[] to Integer[] will never succeed

Ex:

Integer[] a= (Integer[]) new Object[] {}; // this cast will never succeed

Infact you can only cast Object[] to Object or Object[].

currently when you are trying to access data in the main() method, the cast put in by the compiler for you Integer[] will fail at runtime. You don't need the data array, you just need the values from it, which you can get by adding the following method to the vector class.

E getData(int index) {
    return data[index];
}

In this case, compiler will add the cast to individual elements and will provide you the correct values.

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24
1

You really have two options here. Either use data array of Object[] type or create proper generic array. Here is how to create generic array.

    vector(Class<E> clazz) {
        data = (E[])Array.newInstance(clazz, MAX_LEN);
tsolakp
  • 5,858
  • 1
  • 22
  • 28