views:

71

answers:

2

Yesterday, I was designing a Java class which I wanted to be initalized with Lists of various generic types:

TheClass(List<String> list) {
   ...
}

TheClass(List<OtherType> list) {
   ...
}

This will not compile, as the constructors have the same erasure.

I just went with factory methods differentiated by their names instead:

public static TheClass createWithStrings(List<String> list)
public static TheClass createWithOtherTypes(List<OtherType> list)

This is less than optimal, as there isn't a single obvious location where all the different options for creating instances are available.

I tried to search for better design ideas, but found surprisingly few results. What other patterns exist for designing around this problem?

+1  A: 

Note, it would be possible to add method overloading on generic arguments with erasure, although wildcards would make it more difficult.

I would suggest using creation method with a name based on the interpretation of the types. String by itself doesn't have much meaning. createWithThingNames, or something.

Some statically-typed languages do not have method overload at all (deliberately).

Tom Hawtin - tackline
Good point on the method names. 'String' is superfluous, as it's already in the method signature.
Internet Friend
@Internet Friend: "`Strign`" lacks as much meaning in the parameter type as it does in the method name.
Tom Hawtin - tackline
A: 

Differents solutions :

1) with tabs

class TheClass
{
 TheClass(String[] strings)   {}
 TheClass(Object[] others) {}
}

2) with generics

class TheClass<P>
{
 TheClass(P generic) {}
}
Istao
I assume you mean "1) with arrays", but let's not go back there. Generics wouldn't work if the behaviour was different based on element type, which it probable is (and therefore there should probably be some sort of name-based identification).
Tom Hawtin - tackline