0

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)

Doc Holiday
  • 9,928
  • 32
  • 98
  • 151

3 Answers3

2

Pass Arrays.asList(fields).

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2
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.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • I added 'paramBean.setFields(Arrays.asList(form.getFields()));' and got the message: "The method setFields(Collection) in the type DetParameterBean is not applicable for the arguments (List)" – Doc Holiday Feb 02 '12 at 18:44
  • Your setter needs a Set of type DetParameterBean, you can't convert a String into DetParameterBean. What's the content of DetParameterBean? – proko Feb 02 '12 at 18:53
  • It's still the same problem. Your form returns an Array of type String. The bean setter wants a Collection of type DetParameterBean. I am not sure what your task is, but this wont work. Your form might return an Array of type DetParameterBean, or there is a way to create DetParameterBean out of an String (but I doubt that). – proko Feb 02 '12 at 19:05
  • that took away the error...hope it works :)...Now time to send to database – Doc Holiday Feb 02 '12 at 19:13
0

With Guava:

myMethod(ImmutableSet.copyOf(stringArray));

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

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413