0

Consider a plain-old generic class:

class Blob<T>{
    T peanut;
}

To my surprise, the following line of code compiled okay:

Blob c=new Blob();

Why is this allowed, and what type is automatically inserted?

Fresh Air
  • 53
  • 3
  • 1
    in generics you can use raw types, which is a very bad idea btw – ΦXocę 웃 Пepeúpa ツ Apr 05 '17 at 06:59
  • your IDE should at least warns you about: ***Blob is a raw type. References to generic type Blob should be parameterized*** – ΦXocę 웃 Пepeúpa ツ Apr 05 '17 at 07:01
  • You are allowed to this to maintain back-compatibility with Java code before 1.5. If you don't know what ```T``` could be you should use ```?``` like so in the variable type declaration: ```Blob> c```. You cannot use ```?``` in the new clause because there is no way you cannot come out with an appropriate type-parameter since you are the one instantiating it. The minimum common denominator here is using Object: ```new Blob()```. – Valentin Ruano Apr 05 '17 at 18:42
  • In this case you know that ```c``` is actually ```Blob``` so is preferable that you declare it like so instead of ```Blob>```. If you do that then since 1.7 (I think) you can omit the type-parameter in the constructor as it is automatically deduced by the compiler. Thus most likely what you want to write here is: ```Blob c = new Blob<>();``` – Valentin Ruano Apr 05 '17 at 18:42

0 Answers0