Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How use a generic type in constructor of class (Java)

I'm looking for a way to allow the constructor of this class take in an array of a generic type.

public class my
{

   public my(T[] arr)  // how resolve this
   {
      ...
   }
}
like image 238
Ali Bagheri Avatar asked Jan 23 '26 09:01

Ali Bagheri


2 Answers

There are two ways for you to have a type array as a parameter in your constructor. One, you can add the parameter to the class like so...

public class my<T> {

   public my(T[] arr)
   {
        ...
   }

}

Or, your constructor can take in a Type Parameter, like so:

public class my {

   public <T> my(T[] arr)
   {
      ...
   }
}

You can initialize an object of the first class like so:

my<SomeClass> varName = new my<>(arrayOfSomeClass);

And you can initialize an object of the second class like so:

my varName = new <SomeClass>my();

Hope this helps!

like image 161
Kröw Avatar answered Jan 24 '26 21:01

Kröw


I can't think of any situation where I would want a generic constructor in a non-generic class. But hey, here you go:

You just add <T> to the constructor declaration:

public <T> my(T[] arr) {

}

Be careful when you call this constructor. Because it is generic, you can't use primitive types like int or char. You need to use their reference type counterparts, Integer and Character.

like image 38
Sweeper Avatar answered Jan 24 '26 22:01

Sweeper