Balaram Das
Balaram Das

Reputation: 3

How to fill setter method with double[] argument in Java?

public class HealthInsurancePlan {
   
   //variable for setter & getter method
      private double coverage[] = {0.0,0.0};
    
  //setter
      public void setCoverage(double coverage[]){
          this.coverage = coverage;
      }
    
  //getter
      public double[] getCoverage() {
          return coverage;
      }
}
  1. No why following command doesn't work?

  2. What is proper way to fill arguments in the setter method?

    setCoverage(0.1,0.2);

Thx.

Upvotes: 0

Views: 588

Answers (2)

deepakchethan
deepakchethan

Reputation: 5600

You can use Java var args so that it accepts variable number of objects and converts it into array of objects. Update your setter as follows:

 //setter
 public void setCoverage(double... coverage){
    this.coverage = coverage;
 }

and you can just call setCoverage(0.1,0.2)

Upvotes: 1

Tomino
Tomino

Reputation: 475

double[] a = {2.3, 3.4 , 4.5}; 
HealthInsurancePlan plan = new HealthInsurancePlan();
plan.setCoverage(a);

Alternatively you can use:

plan.setCoverage(new double[]{2.3, 3.4 , 4.5});

Upvotes: 1

Related Questions