0

I was wondering whether I understand the following Java issue correctly. Given a generic collection, if I do

public class HashTable<V extends Comparable<V>> implements HashTableInterface<V> {
    private V[] array;

    public HashTable() {
        this.array = (V[]) new Object[10];
    }
}

the code breaks, throwing an exception: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;

However, if I change this.array = (V[]) new Object[10]; to this.array = (V[]) new Comparable[10]; then it works.

The way I understand it is that upon compilation the resulting bytecode will not have any generic references as they are replaced by Java's type erasure.

this.array = (V[]) new Object[10]; breaks because the line will implicitly be replaced by this.array = (Comparable[]) new Object[10]; which will then result in a cast exception as Object does not extend Comparable. It is resolved by changing it to an array of Comparables.

Is this correct? Thanks!

4
  • Object doesn't extends Comparable so it cannot be cast to V Commented Aug 27, 2012 at 6:28
  • 1
    That's pretty much how it works. Commented Aug 27, 2012 at 6:28
  • 1
    It seems to me that it has nothing to do with array in fact. Even you have a single object reference, it is the same. Because you have <V extends Comparable<V>>, after type erasure, V will be replaced by Comparable<V> (instead of Object), which caused the issue you faced Commented Aug 27, 2012 at 7:20
  • I agree Adrian. Just wanted to use the example I had at hand for explanation. Commented Aug 27, 2012 at 7:35

1 Answer 1

3

The type variable is erased to the erasure of its left most bound. So V is erased to |Comparable<V>| = Comparable. If you changed the bound to Object & Comparable<V> the erasure would become |Object| = Object and (V[]) new Object[10] would work also.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.