Why is the generic array code compiled cleanly?

After refactoring the legacy code and starting working with generics, I found that the functions look like this:

T[] splitXXX() { //blah blah } 

Produces many class exclusions, since jdk does not actually support arrays of typical types. And I am wondering - why is this code compiled in java? Is it backward compatible? (this would save me a lot of time researching if I could find these errors at compile time rather than at run time). What am I missing?

+4
source share
2 answers

If a type variable only appears in the return type, this is pretty dangerous. for instance

 public static <T> T foo(){ ... } // usage String s = foo(); Integer i = foo(); 

The compiler believes that if a programmer assigns T to String , he probably knows what he is doing, so itโ€™s pretty safe to conclude that T=String . Heck, in fact there are no restrictions, the result of foo() can be assigned to any type.

But a programmer may not always know what he is doing; he relies on a strongly typed compiler to catch some typing errors that he might inadvertently commit.

0
source

Just because you cannot make new T[...] does not mean that you cannot have a variable of type T[] , just as you cannot make new T() does not mean that you cannot have a variable of type T

It is perfectly possible to have the correct code that has methods that return T[] :

 class Something<T> { T[] foo; Something(T[] in) { foo = in; } T[] splitXXX() { return foo; } } 

Produces many cool exercises,

Well, if it throws exceptions, it means that you are doing something wrong. You didnโ€™t show us which code throws exceptions or something else, but you are likely making throws that are not valid in your code.

0
source

All Articles