Is it possible to remove general type parameters from an object constructor in Java?

In Java it is tedious to write:

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

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

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

And again skip the general options.

You can create a static method that can spoof it like this:

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

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

Is it possible to build type inference in the constructor to avoid hacking?

I was thinking of something like:

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

But then you come across generic types of collisions. Anyone have any thoughts?

+5
source share
5 answers

Usually has a helper method that will imply types for you.

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

then it doesn't look like such a hack.

, Java Pair.;)

+7

Java 7 "":

List<String> strings = new ArrayList<>();

Map<String, Int> map = new HashMap<>();

Map<String, List<String>> lolmap = new HashMap<>();
+3

, , , . , , , , (, X-Y):

Pair<float,float> myCoords = new Pair(3,4);

; Pair<float, float>, , , , Pair<int,int>, , , , ). Java generics, AFAIK, , , int float. , , .

+1

, , . Java ( ):

import java.util.*;

public class Main {
  public static void main(String[] args) {
    ArrayList a = new ArrayList();
    a.add(1);
    ArrayList<String> b = a;
    System.out.println(b.get(0));
  }
}

But the compiler cannot deduce the type now, but the assignment is compatible with b. Try running it and a runtime error will occur.

+1
source

I prefer things to be explicit. When conclusions are drawn, they may be inferred incorrectly or the method may be used incorrectly without any notice, as the system indicates how to handle invalid arguments.

0
source

All Articles