Doc Holiday
Doc Holiday

Reputation: 10254

Variable must provide either dimension expressions or an array initializer error

For testing purposes, I harded coded a bean array so I can pass variables to the database. I'm now pulling the variables from a form and want to set them in the bean array if they are not null. I assume my syntax is wrong.

Hardcode:

CriteriaBean[] filters = new CriteriaBean[]
{
    new CriteriaBean("YEAR","=","2012"),
    new CriteriaBean("LOCATION","in","('XXX','YYY')"),
    new CriteriaBean("TOM","is","not null") 
};

I was trying to do something like this and got the error:

 CriteriaBean[] filters = new CriteriaBean[]
           {
            if (form.getYear() != null) 
            {   
            new CriteriaBean("YEAR","=","2012")
            }


           };

CriteriaBean

public class CriteriaBean
    {
public static final CriteriaBean[] EMPTY_ARRAY = new CriteriaBean[0];

private String fieldName;
private String value;
private String operation;

public CriteriaBean() { } 
public CriteriaBean( String field, 
                              String op, 
                              String val ) 
{
   this.fieldName = field; 
   this.operation = op;
   this.value = val;
}



public String getName() { return this.name; }
public String getOp() { return this.op; }
public String getVal() { return this.val; }

public void setName(String val) { this.name = val; }
public void setOp(String val) { this.op = val; }
public void setVal(String val) { this.val = val; }

Is there a better way to do this??

Upvotes: 1

Views: 18437

Answers (1)

Bohemian
Bohemian

Reputation: 425013

Close! Try this:

CriteriaBean[] filters = form.getWySelect() == null
    ? new CriteriaBean[] {}
    : new CriteriaBean[] {
        new CriteriaBean("WORKLOAD_YEAR","=","2012")
      };

This code uses the ternary syntax to use alternate initializers depending on the condition.

Upvotes: 4

Related Questions