2 years ago

#63674

test-img

zhuangjingwen

ClassCastException when using wildcard in java

I got ClassCastException when running java code below:

    public static void main(String[] args) {
        String text = "{" +
                "\"number\": 1" +
                "}";
        // method1
        Integer integer = get();
        String number1 = String.valueOf(integer);
        // method2
        String number2 = String.valueOf(get());
    }

    static <T> T get() {
        return (T) (new Integer(0));
    }
}

And the exception:

Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class [C (java.lang.Integer and [C are in module java.base of loader 'bootstrap')

Why method2 does not work?

java

classcastexception

0 Answers

Your Answer

Accepted video resources