Doc Holiday
Doc Holiday

Reputation: 10254

Need to pass a String array to a Set

Hello guys I need to pass a string array over to a setter that takes a Set. Not sure how to pass it over. Thanks

THis is my form:

  public String[] getFields() { return fields; }
public void setFields(String[] s) 
{ 
    fields = s; 
    //System.out.println("form Array length " + s.length);  
}

and here is the bean:

private Set<FieldBean> fields;

   public void setFields( Collection<FieldBean> val )
{
    t
    if( fields == null ) fields = new HashSet<FieldBean>();
    fields.addAll( val );
}

Action code:

ParameterBean paramBean = new ParameterBean();  
form.getFields()  y

        paramBean.setFields(Arrays.asList(form.getFields()));  //Need bean set here

got a message that stated: The method setFields(Collection) in the type ParameterBean is not applicable for the arguments (List)

Upvotes: 0

Views: 1849

Answers (3)

Louis Wasserman
Louis Wasserman

Reputation: 198033

With Guava:

myMethod(ImmutableSet.copyOf(stringArray));

(Simpler, faster, and less memory-intensive than HashSet.)

Upvotes: 0

Bozho
Bozho

Reputation: 597076

new HashSet<..>(Arrays.asList(array)); 

will give you a set. But since you already have the addAll(..) method, you just need a collection, which is Arrays.asList(array)

Btw, normally a setter just takes a value and sets it. Having this kind of logic within the setter is not always a good idea. So check if you could make it a simple setter and use the first line of my answer.

Upvotes: 2

SLaks
SLaks

Reputation: 887385

Pass Arrays.asList(fields).

Upvotes: 2

Related Questions