2016-08-03 3 views
1

Divide two String into substrings and pair them로 경기를하고있어 멀리있어. 내가 너무 멀리 추론 규칙을 스트레칭하고 있습니까제네릭 형식 유추가 작동하지 않습니까?

/** 
* 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", ";")); 
} 

- 문제는 Collectors.toList호환되지 않는 유형으로 거부한다? 이 문제를 어떻게 해결할 수 있습니까?

답변

7

추가 다이아몬드 연산자 하나의 생성자

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

Pair에! 나는 그런 바보 같은 느낌이었다. – OldCurmudgeon

+0

이유에 대해서는 [원시 유형 피하기] (http://www.javapractices.com/topic/TopicAction.do?Id=224)를 참조하십시오. – OldCurmudgeon