Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is is possible to remove generic type parameters from object constructor in Java?

In Java it is tiring to have to write:

Pair<String, String> pair = new Pair<String, String>("one", "two");

It would be nice if the types were inferred for you so you could at least do this:

Pair<String, String> pair = new Pair("one", "two");

And skip the generic params again.

You can make a static method that can cheat around it like so:

public static <T, S> Pair<T, S> new_(T one, S two) {
    return new Pair<T, S>(one, two);
}

And then use it like: Pair.new_("one", "two").

Is it possible to build the type inferencing into the constructor so that hack can be avoided?

I was thinking of something like:

public <S,T> Pair(S one, T two) {
    this.one = one;
    this.two = two;
}

But then you run into generic type collisions. Does anyone have any thoughts?

like image 875
jjnguy Avatar asked Jun 13 '11 16:06

jjnguy


1 Answers

It s common to have a helper method which will imply the types for you.

Pair<String, String> pair = Pair.of("one", "two");

then it doesn't seem like such a hack.

It would also be nice if Java had a built in Pair class. ;)

like image 191
Peter Lawrey Avatar answered Sep 25 '22 06:09

Peter Lawrey