[英]What is the best way to treat an object like an iterable in Java?
What is the best way to treat a single object as iterable? 将单个对象视为可迭代的最佳方法是什么?
For example, in the following case... 例如,在以下情况下...
public void fun(Object o) {
fun(new TempList(o));
}
public void fun(Iterable<Object> os) {
try {
for(Object o : os)
// Write to server
System.out.println(o);
} catch(Exception e) {
// log e
}
}
UPDATE: 更新:
Rewording this part. 重述此部分。
A function already exists that takes an iterable of things and processes them ( fun(Iterable<Object> os)
). 已经存在一个需要对事物进行迭代并对其进行处理的函数( fun(Iterable<Object> os)
)。 I am adding an alias for this function that takes a single item instead ( fun(Object o)
). 我为此函数添加了一个别名,而不是单个项目( fun(Object o)
)。 This function will be called a lot by different instances, so I want the most resource efficient way to call the Iterable function with a single item (whatever creates the least trash/gets cleaned up the fastest). 此函数在不同的实例中会被大量调用,因此我想以最省资源的方式使用单个项目调用Iterable函数(无论创建最少的垃圾回收/最快清理)。
Or, exactly as the question title says, What is the best way to pass an Object
to a function that requires an Iterable<Object>
? 或者,正像问题标题所说的那样,将Object
传递给需要Iterable<Object>
的函数的最佳方法是什么?
使用Collections.singleton(item)
也许您可以看看Collections.singletonList(object)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.