如何生成由函数支持的列表? [英] How can I generate a List backed by a Function?

查看:115
本文介绍了如何生成由函数支持的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数 myFunction 函数< Integer,T> ,我想要构造一个对象 mylist 大小大小,执行 List< T> 也许某种不可变的列表接口),由函数支持,在 mylist.get(i)== myFunction.apply(i)。



我可以手动执行此操作,但是有一些(Guava)代码可以做到这一点吗?

解决方案使用 java.util.AbstractList

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




$ b $ p
$ b

结果不一定是不可变的,因为函数输出可能有所不同很有可能,你完全可以摆脱 Function ,只需在函数 code> AbstractList 实现。


I have a function myFunction of Function<Integer, T>, and I want to construct an object mylist of size size, implementing List<T> (or maybe some kind of immutable list interface), backed by the function, in the sense that mylist.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 the Function in your AbstractList implementation.

这篇关于如何生成由函数支持的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆