user1813228
user1813228

Reputation:

Pass Collection of string to (String... values)

I have a very simple question.

This below method-

newColumnsPredicate

takes input as String... colNames

Below is the method signature as well-

public static SlicePredicate newColumnsPredicate(String... colNames) {

   //Some code

}

And I have below collection of strings that I wanted to use in the above method-

final Collection<String> attributeNames

So I decide to use it something like this-

newColumnsPredicate(attributeNames.toString());

This is the right way to do this? As after I run my program, I don't get any data back so I am suspecting it might be possible the way I have added is wrong.

Can anyone help me with this?

Upvotes: 0

Views: 796

Answers (3)

Jonathan S. Fisher
Jonathan S. Fisher

Reputation: 8817

Wouldn't the toArray()function be useful here?

public void test() {
    Collection<String> collection = new HashSet<>();
    newColumnsPredicate(collection.toArray(new String[collection.size()]));
}

public static SlicePredicate newColumnsPredicate(String... colNames) {
    //stuff
}

EDIT: Whoops, didn't see the other guy answered in the same way.

Upvotes: 0

GaryF
GaryF

Reputation: 24330

String... is a vararg parameter. It is used to indicate that the parameter should either be an array of Strings, or as many String arguments as you like.

Calling toString() on the collection will merely return one string that combines all of the Strings it contains.

You should instead write something that converts your collection to an array, and then pass that in, like:

attributeNames.toArray(new String[attributeNames.size ()])

Upvotes: 5

Pradeep Pati
Pradeep Pati

Reputation: 5919

No, When you do a attributeNames.toString(), you are passing a single String to the method, with a square bracket around them, like "[a, b, c]", Where as your program expects something like "a", "b", "c".

Upvotes: 0

Related Questions