tags:

views:

125

answers:

3

What should be the return type of a zip function? (zip as in most other languages, e.g. read here)

I thought about some Pair-type but that does not exist in Java. It is often states that this is because a specialized Pair-class is better than a general one (see this question). However, this is not possible in a general zip function.

+1  A: 

No, there isn't explicitly a pair (or any tuple) in the standard JRE.

There was a discussion on the subject on the javaposse Google group that you might be interested in, that links off to a post by Dick Wall on why Java needs a Pair and a Triple, plus a similar question asked here.


Update - original question was whether there was a Pair in Java. This answer may no longer make sense.

Brabster
A: 

Here is a start.

public abstract class Pair
{
    private T1 first;
    private T2 second;

    public Pair(T1 first, T2 second)
    {
        this.first = first;
        this.second = second;
    }

    public T1 getFirst()
    {
        return first;
    }

    public T2 getSecond()
    {
        return second;
    }
}
dwb
A: 

Since you appear to be determined to ignore people with many years Java experience, here is code which does the same as the zip function in python.

public static <T> List<List<T>> zip(List<T>... lists) {
    List<List<T>> zipped = new ArrayList<List<T>>();
    for (List<T> list : lists) {
        for (int i = 0, listSize = list.size(); i < listSize; i++) {
            List<T> list2;
            if (i >= zipped.size())
                zipped.add(list2 = new ArrayList<T>());
            else
                list2 = zipped.get(i);
            list2.add(list.get(i));
        }
    }
    return zipped;
}

public static void main(String[] args) {
        List<Integer> x = Arrays.asList(1, 2, 3);
        List<Integer> y = Arrays.asList(4, 5, 6);
        List<List<Integer>> zipped = zip(x, y);
        System.out.println(zipped);
}

Prints

[[1, 4], [2, 5], [3, 6]]
Peter Lawrey
To translate your post into an answer to my question: I can just use `List<T>` instead of `Pair<T,T>`. Still doesn't work though if I want to `zip` lists of different types.
Albert
All types extend Object and you can use this for all types.
Peter Lawrey