java - Are generic type parameters converted to Object for raw types? -


consider piece of code:

public class main {     public static void main(string[] args) {         cat<integer> cat = new cat();         integer i= cat.meow();         cat.var = 6;     } } public class cat<e> {     public e var;     public e meow() {         return null;     } } 

as per understanding since i've not specified type parameter on lhs, taken object. , cat should become cat<object> because variable declaration make sense t must translate class/interface reference. correct understanding of how works? how type parameter t handled in case of raw types?

i've discussed on chat , got following explanation way on head:

generics works because types erased. consider t erasure of #0-capture-of-object. when t isn't specified (rawtyped), #0-capture-of-(nothing)

what #0-capture-of-(nothing) mean?

side note: since generic types implemented compile time transformations easier understand them if 1 see final translated code. know way see translated code (not byte code) class?

no,

raw types not if paramterized object, nor wildcard types (<?>).
raw types, generics turned off.

this code compiles (with warnings):

cat c1 = new cat<string>(); cat<integer> c2 = c1; 

this code not:

cat<? extends object> c1 = new cat<string>(); // btw: same cat<?> cat<integer> c2 = c1; // error 

neither this:

cat<object> c1 = new cat(); cat<integer> c2 = c1; // error 

as type of var:

the type of field after compilation whatever upper-bound of parameter (object if none specified). compiler if access var?

cat<string> c1 = ... string c1var = c1.var; 

this code compiles without error, compiler compile this:

cat c1 = ... string c1var = (string) c1.var; 

as can see, var treated field of type object, with generics, compiler automatically inserts type-safe casts. that's all. if use raw types, have yourself. either way, when put cat stores integer in cat<string> variable, runtime exception if try read var.

a quiz

now @ declaration of collections.max. why think parameter defined t extends object & comparable<? super t>?

answer encoded in rot13:

fb gung nsgre pbzcvyngvba gur erghea glcr vf bowrpg, abg pbzcnenoyr. guvf vf arrqrq sbe onpxjneqf pbzcngvovyvgl (gur zrgubq vgfrys vf byqre guna trarevpf).

edit:

here example stumbled upon:

class foo<t> {     public <v> v bar(v v) { return v; } }  //compiles foo<object> foo = new foo<object>(); integer = foo.bar(1);  //compiles foo<?> foo = new foo<string>(); integer = foo.bar(1);  // fails foo foo = new foo(); integer = foo.bar(1); // error: object cannot converted integer 

using no parameters disables generics entirely.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -