简体   繁体   English

将单个元素传递给接受集合的方法

[英]Pass Single Element to Method that Accepts a Collection

There is a method that accepts a collection. 有一种接受集合的方法。 I need to pass a single element to that method. 我需要将一个元素传递给该方法。 What is the best way to do this? 做这个的最好方式是什么? Which implementation of collection should I use? 我应该使用哪种集合实现?

java.util.Collections.singleton()

As per my understanding, you have a method like this: 根据我的理解,你有一个像这样的方法:

public void someMethod(Collection c)

and you need to pass a single element to it(say MyObject). 你需要传递一个元素(比如MyObject)。

There are two options here: 这里有两个选项:

  1. Create a List, add MyObject to it and then pass the List to method. 创建一个List,向其添加MyObject,然后将List传递给方法。

  2. If possible, use polymorphism! 如果可能,使用多态! - Create a new method with MyObject as parameter: - 使用MyObject作为参数创建一个新方法:

    public void someMethod(MyObject obj); public void someMethod(MyObject obj);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM