0

I'm learning to work with generics, I can't understand why this is throwing an exception:

My 'GenericList' class:

package com.company.generics;

public class GenericList<T extends Number>{

    private T[] items = (T[]) new Object[10];
    private int count;

    public void add(T item){
        items[count++] = item;
    }

}

My main class:

package com.company;

import com.company.generics.GenericList;

public class Main {

    public static void main(String[] args) {

        GenericList<Integer> g = new GenericList<>();

    }
}

Exception thrown:

Exception in thread "main" java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class [Ljava.lang.Number; ([Ljava.lang.Object; and [Ljava.lang.Number; are in module java.base of loader 'bootstrap')
    at com.company.generics.GenericList.<init>(GenericList.java:4)
    at com.company.Main.main(Main.java:9)
3

1 Answer 1

2

Since T has an upper bound, the cast has an upper bound and is actually resolving to Number rather than Object. You'll have to declare your array of that type instead of Object.

private T[] items = (T[]) new Number[10];

And according to Effective Java, you may have to add a @SupressWarnings("unchecked") to that assignment. I didn't actually try it however.

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

8 Comments

A change from when?
Well I don't recall it working that way before. I've always just used Object[] like the op has. But I might be misremembering.
I feel like it's always resolved to the most specific type that can be inferred at compile time, though that doesn't come up too often.
Because the type is correctly declared as T[], so you want to match it. It's safer to do it that way because a return items[x] will return the correct type. C.f. Effective Java by Joshua Bloch, Item 26 "Favor Generic Types."
I'm sure the OP's example has been reduced to the minimum for the sake of the question. :) I don't see any practical use for a class with only an add() method but no way to retrieve the values.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.