Pass a single element to a method that accepts a collection

There is a method that accepts a collection. I need to pass one element to this method. What is the best way to do this? Which collection implementation should be used?

+4
source share
2 answers

java.util.Collections.singleton()

+14
source

As I understand it, you have this way:

 public void someMethod(Collection c) 

and you need to pass one element to it (e.g. MyObject).

There are two options here:

  • Create a list, add MyObject to it, and then pass the List to method.

  • Use polymorphism if possible! - Create a new method with the MyObject parameter as:

    public void someMethod (MyObject obj);

0
source

Source: https://habr.com/ru/post/1390584/


All Articles