Can't Tell
Can't Tell

Reputation: 13476

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?

Upvotes: 4

Views: 952

Answers (2)

irreputable
irreputable

Reputation: 45453

java.util.Collections.singleton()

Upvotes: 14

Manish
Manish

Reputation: 3968

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).

There are two options here:

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

  2. If possible, use polymorphism! - Create a new method with MyObject as parameter:

    public void someMethod(MyObject obj);

Upvotes: 0

Related Questions