简体   繁体   English

用Java将对象视为可迭代对象的最佳方法是什么?

[英]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.

相关问题 在可迭代中断言项目的最佳方法是什么 - What is the best way to assert items in an iterable 在Java中维护事务列表的最佳方法是什么(事务对象具有ID,日期,金额等字段) - what is the best way to maintain a list of Transactions in java (transaction object having fields like id, date, amount etc) 最佳实践:什么是处理字节协议的最佳方法 - Best practices: What's the best way to treat byte protocol Java:读取序列化对象的最佳方法是什么? - Java: What is the best way to read a Serialized object? 在Java中清理Object的最佳方法是什么? - What is the best way to clean up an Object in Java? 在 Java 中,确定 object 大小的最佳方法是什么? - In Java, what is the best way to determine the size of an object? Java:将对象数据成员写入文件的最佳方法是什么? - Java: What is the best way to write object data members to a file? 在Java中将List <Long>对象转换为long []数组的最佳方法是什么? - What is the best way of converting List<Long> object to long[] array in java? 使用页面对象模型(java)处理导航的最佳方法是什么 - What is the best way to handle navigation using page object model (java) (de)将Java对象序列化为文件的最佳方法是什么 - What's the best way to (de)serialize a Java object to file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM