Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problems with understanding generics

Tags:

java

generics

I have wrote the following code:

public class Test
{   
    public static void main(String args[]) throws ParseException 
    {
        System.out.println(new Generic<Integer>("one").type);  //outputs "one"
    }
}

class Generic<T>
{
    public T type;

    public Generic(Object obj)
    {
        type = (T)obj;
    }
}

And i thought i will get an exception while doing the cast, but i didnt. I get the output: "one". But if i do new generic<Integer>, type become a variable of type Integer, so how can i cast the String "one" to T and store it in the variable type in my generic class without getting an exception? An explanation would be great.

like image 660
kai Avatar asked Aug 01 '26 12:08

kai


1 Answers

There is no exception because type erasure removes any checking of the Integer type from your code. Since println takes Object the compiler doesn't need to insert a cast, and the code simply erases to:

System.out.println(new Generic("one").type);

Try the following assignment instead:

Integer i = new Generic<Integer>("one").type;

In that case you'll get a ClassCastException because the code erases to:

Integer i = (Integer)new Generic("one").type;

Notice that switching the types behaves differently. This will throw a ClassCastException:

System.out.println(new Generic<String>(123).type);

That's because the println(String) overload is used, so the code erases to:

System.out.println((String)new Generic(123).type);
like image 188
Paul Bellora Avatar answered Aug 04 '26 01:08

Paul Bellora



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!