OldCurmudgeon OldCurmudgeon - 1 year ago 55
Java Question

Generics type inference not working?

Playing with Divide two String into substrings and pair them and got this far. Problem is the

Collectors.toList
is rejected with incompatible types -

/**
* General pair of items.
*
* @param <P> - Type of the first item in the pair.
* @param <Q> - Type of the second item.
*/
static class Pair<P, Q> {
final P p;
final Q q;

public Pair(P p, Q q) {
this.p = p;
this.q = q;
}

@Override
public String toString() {
return "{" + p + "," + q + "}";
}
}

/**
* Gets the `n`th item is present in the array - otherwise returns null.
*
* @param a - The array
* @param n - Which one in the array we want.
* @param <T> - The type of the array entries.
* @return - The `n`th entry in the array or null if not present.
*/
private static <T> T n(T[] a, int n) {
return n < a.length ? a[n] : null;
}

/**
* Pairs up each element in the arrays.
*
* @param ps - The `P` array.
* @param qs - The `Q` array.
* @param <P> - The type of the elements in the `P` array.
* @param <Q> - The type of the elements in the `Q` array.
* @return A list of `Pair`s of each element.
*/
static <P, Q> List<Pair<P, Q>> pairUp(P[] ps, Q[] qs) {
return IntStream.range(0, Math.max(ps.length, qs.length))
.mapToObj(i -> new Pair(n(ps, i), n(qs, i)))
.collect(Collectors.toList());
}

/**
* Splits the two strings on a separator and returns a list of Pairs of thje corresponding items.
*
* @param a - The first string.
* @param b - The second string.
* @param separator - The separator.
* @return - A List of Paired up entries from `a` and `b`.
*/
private static List<Pair<String, String>> fold(String a, String b, String separator) {
return pairUp(a.split(separator, -1), b.split(separator, -1));
}

public void test() {
System.out.println(fold("1;2;3;4", "Value1;Value2;Value whitespace", ";"));
}


Am I stretching the inference rules too far? How can this be fixed?

Answer Source

Add diamond operator to Pair constructor

new Pair<>(n(ps, i), n(qs, i))