Can I remove generic type parameters from object constructors in Java?

In Java, you must write:

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

It would be nice to infer these types for you, so you can at least do this:

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

And skip the general parameters again

You can create a static method that can cheat like this:

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

Then use it: pair new _ (“one”,“two”).

Can type inference be built in constructors so that hacking can be avoided?

What I think is:

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

But you will encounter generic conflicts Does anyone have an idea?

Solution

There is usually a help method that will hint at your type

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

Then it doesn't seem to be such a hacker

It would also be nice if Java had a built - in pair class

The above is collected by programming house for you. Can you delete generic type parameters from object constructors in Java? I hope this article can help you solve whether you can delete generic type parameters from object constructors in Java? Program development problems encountered.

If you think the content of the programming home website is good, you are welcome to recommend the programming home website to programmers and friends.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>