Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics - T place holder

 
adam Lui
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
is it legal to declare a <T> as object/ primitive type INSIDE a method, or even as a return type?
e.g.



i want to figure it out but I dont know how to write a testing code for this case.
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you can declare a local reference variable using a type parameter, so your "T obj1" line is indeed valid syntax. But type parameters are always object types (i.e. class or interface), so obj1 will never be a primitive.

However, "new T()" is not allowed. Type parameters are only for compile-time (i.e. static) type checking, but they are "erased" during compilation and do not exist at runtime. As a result of this type erasure, the program does not know what T is at run-time, so it can't instantiate an object of type T. (This is similar to the other question you posed regarding the ClassCastException with toArray()'s return value.)
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's something you can play with:



Yours,
Bu.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic