简体   繁体   中英

How to use setters and getters for array

okay so on my class diagram it shows

void setVegetable( String veg[] )
String veg[] getVegetables()

Just wondering how I would code the statement for this?

public void setVegetables( String veg[] )  
{  
}

also how would I write the instance variables?
do I still write it as

private string vegetables = "";

The simple answer is to use a member definition like this:

private String[] vegetables;

And a setter like this:

public void setVegetables( String veg[] ) {  
    vegetables = veg;
}

However you should keep in mind that a array is modifiable meaning that if you store the array directly like in the setter described above the caller will still be able to modify the content of the array so it's a good practice to copy the array content if you want a better encapsulation. Though this will have impact on performances if you manipulate large arrays. In this case the setter and getter will look like this

public void setVegetables( String veg[] ) {  
    vegetables = Arrays.copyOf(veg, veg.length);
}

public String[] getVegetables() {  
    return Arrays.copyOf(vegetables, vegetables.length);
}

You would need something like

private String[] vegetables;

and the setter method

public void setVegetables( String[] veg )  { this.vegetables = veg; )

or suffer a compile error - An array of String 's is not the same as a String .

I would change the variable:

private String vegetables;

to an array:

private String vegetables[];

then normally set and get the instance array using the setter and getter methods.

应该是这样的:

public void setVegetables( String[] veg ) { }

您可以在初始化时为本地变量赋值,如下所示:

private String[] vegetables = new String[]{"Carrot", "Parsnip"};

As per your class diagram, the instance variable you are looking at is a String array. So the instance member has to be a String[] as well. The declaration should be like

private String[] vegetables;
public void setVegetables( String vegetables[] ) {  
    this.vegetables = vegetables;
}

public String[] getVegetables() {  
    return vegetables;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM