2

私はの関数を持っており、myFunctionその関数に裏打ちされた、という意味での実装(またはある種の不変のリストインターフェイス)を使用して、サイズFunction<Integer, T>のオブジェクトを構築したいと考えています。mylistsizeList<T>mylist.get(i) == myFunction.apply(i)

これは手動で行うことができますが、同じことを行う(Guava)コードはありますか?

4

2 に答える 2

5

使用するだけjava.util.AbstractListです:

 new AbstractList<T>() {
   public T get(int i) {
     Preconditions.checkElementIndex(i, size);
     return function.apply(i);
   }
   public int size() {
     return size;
   }
 }

関数の出力は変化する可能性があるため、結果は必ずしも不変ではありません。おそらく、 を完全に削除してFunction、実装に の実装を記述するだけで済みます。FunctionAbstractList

于 2013-02-26T21:22:13.163 に答える
1

おそらく、リストの代わりにIterator<T>.

// Example simple Function that returns each element from the array.
static class Function<T> {
    final T[] t;
    Function(T[] t) {
        this.t = t;
    }
    T apply (Integer i) {
        return t[i];
    }
}

static class FunctionIterator<T> implements Iterator<T> {
    final Function<T> f;
    Integer i;
    Integer to;
    Integer step;

    FunctionIterator(Function<T> f, Integer from, Integer to) {
        this.f = f;
        if ( to > from ) {
            step = 1;
            i = from;
            this.to = to;
        } else {
            step = -1;
            i = to;
            this.to = from;
        }
    }

    @Override
    public boolean hasNext() {
        return i != to + step;
    }

    @Override
    public T next() {
        T next = f.apply(i);
        i += step;
        return next;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException("Not supported.");
    }
}

このコードは、Iterator. あなたはIterableそれから非常に簡単に作ることができます. これは、それを行う方法の優れたきちんとした例です

于 2013-02-26T21:12:27.203 に答える