Ali Bagheri
Ali Bagheri

Reputation: 3419

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
   {
      ...
   }
}

Upvotes: 2

Views: 6523

Answers (3)

Kröw
Kröw

Reputation: 315

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!

Upvotes: 6

Manmohan Singh
Manmohan Singh

Reputation: 31

add <T> along with the name of the class my

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

Upvotes: 1

Sweeper
Sweeper

Reputation: 271575

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.

Upvotes: 2

Related Questions