如何生成由函数支持的列表? [英] How can I generate a List backed by a Function?
问题描述
我有一个函数 myFunction
函数< Integer,T>
,我想要构造一个对象 mylist
大小大小
,执行 List< T>
也许某种不可变的列表接口),由函数支持,在
我可以手动执行此操作,但是有一些(Guava)代码可以做到这一点吗?
java.util.AbstractList
:新的AbstractList< T>(){
code> AbstractList 实现。
public T get(int i){
Preconditions.checkElementIndex(i,size);
return function.apply(i);
}
public int size(){
return size;
$ b $ p
$ b结果不一定是不可变的,因为函数输出可能有所不同很有可能,你完全可以摆脱
Function
,只需在函数 I have a function
myFunction
ofFunction<Integer, T>
, and I want to construct an objectmylist
of sizesize
, implementingList<T>
(or maybe some kind of immutable list interface), backed by the function, in the sense thatmylist.get(i) == myFunction.apply(i)
.I can do this manually, but is there some (Guava) code which does the same?
解决方案Just use
java.util.AbstractList
:new AbstractList<T>() { public T get(int i) { Preconditions.checkElementIndex(i, size); return function.apply(i); } public int size() { return size; } }
The result would not necessarily be immutable, since the function output could vary. In all likelihood, you could get rid of the
Function
entirely, and just write the implementation of theFunction
in yourAbstractList
implementation.这篇关于如何生成由函数支持的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!