How do i create a generic type which accepts only a type of Integer, Long and String.
I know we can restrict a type for a single class or by implementing an interface with below code
public class MyGenericClass<T> where T:Integer{ }
or to handle int,long but not string
public class MyGenericClass<T> where T:struct
Is it possible to create a generic which accepts only a type of Integer, Long and String?
Using generics, primitive types can not be passed as type parameters. In the example given below, if we pass int primitive type to box class, then compiler will complain. To mitigate the same, we need to pass the Integer object instead of int primitive type.
So, anything that is used as generics has to be convertable to Object (in this example get(0) returns an Object ), and the primitive types aren't. So they can't be used in generics.
Java generics have the restriction that they must be instantiated with a user-defined class. Hence generics may not be instantiated with primitive types, such as ints. If you want to use a primitive type, use its wrapper type instead, such as Integer.
Using generics allows us to write a typesafe code that will work with a wide range of primitives and objects.
You could potentially not have the constraints in the class declaration, but do some type-checking in a static constructor:
public class MyGenericClass<T>
{
static MyGenericClass() // called once for each type of T
{
if(typeof(T) != typeof(string) &&
typeof(T) != typeof(int) &&
typeof(T) != typeof(long))
throw new Exception("Invalid Type Specified");
} // eo ctor
} // eo class MyGenericClass<T>
Edit:
As Matthew Watson points out above, the real answer is "You can't and shouldn't". If your interviewer believes that to be incorrect, then you probably don't want to work there anyway ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With