user590849
user590849

Reputation: 11765

How to make constructors with different generics in java

I have a class and the following are its constructors

public Data(ArrayList<String> row){
}

public Data(ArrayList<Integer> row){
}

The above is giving me an error saying :

Method Data(ArrayListList) has the same erasure Data(ArrayList)
as another method in type Data.

I even tried doing :

public Data(ArrayList<?> rows) {

    if (rows.get(0) instanceof String) {

        initializeData(rows);

    }

}

But in the above, I then have to convert the whole ArrayList into a ArrayList. Which I think is in-efficient.

I am trying to instantiate a class either with ArrayList or with ArrayList (the user has the choice).

Data = new Data( new ArrayList< String >() );

Data = new Data( new ArrayLIst< Integer >() ); So both of the above should work. Based on the type of input parameter passed the class would then call different methods.

Is there are better to achieve what I want ?

Thank you in advance.

Upvotes: 6

Views: 1317

Answers (3)

scottb
scottb

Reputation: 10084

Generics are implemented in Java by erasure. This means that the generic type information exists only at compile time and that the compiler alone has the responsibility for assuring type safety when using generics. When your program runs, the generic type information simply does not exist.

The runtime class literal for

List<String>

and for

List<Integer>

are both List.class.

This is why the compiler will not allow you to provide an overloaded constructor with the collections that differ only in their generic type parameters. From the perspective of the run time environment, both these parameter types are the same.

As a workaround, you can wrap each of the generic ArrayList types in its own distinct helper class. This will allow you to provide overloaded constructors that take each of the helper classes as their parameters.

Upvotes: 7

BevynQ
BevynQ

Reputation: 8259

You can do this by extending ArrayList to concrete types,

eg

public class IntegerArrayList extends ArrayList<Integer>{};

however the situations in which you actually want to do this are very rare are you sure you need to do this how would the constructors differentiate from each other?

Upvotes: 0

denis.solonenko
denis.solonenko

Reputation: 11765

You cannot do that, the error is telling you that generics will be erased at compile time and you would end up with 2 constructors with the same signature.

A few options you can explore:

public Data(String[] row)
public Data(Integer[] row)

Or:

public class Data<T> {
    public Data(List<T> row);
}

new Data<String>(new ArrayList<String>())

Upvotes: 1

Related Questions