Generic class on two types
I开发者_如何学编程 want to create a Java class with two generic types.
public class BinaryContractInfo<T, U>
The thing is that I would like U
to be either the same type of T
or T[]
.
Basically I would like to know if T extends T[]
or vice versa. Then I could do something like
public class BinaryContractInfo<T, U extends T[]>
Is that possible? Is there a way to do that?
You cannot specify a type as being either T
or T[]
Instead you can use varargs
public void method(T... ts);
which can be called either
method(t);
method(t1, t2, t3);
T[] ts =
method(ts);
For return types you can specify
public T[] method();
if the caller assumes there is only one return value
T t = method()[0];
No, AFAIK, you can't do that, not to mention that arrays and generics don't play well together. The simplest thing would be to wrap your array in a collection type (List
or a very thin wrapper over an array), if you are allowed to do it that is.
Also, why not just use T[]
directly in your code instead of having a separate type parameter for it? If you can't, then do explain why you can't.
精彩评论