简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM