Search code examples
javaarraylistgetter-setter

Getters and Setters for ArrayLists in Java


How would I go about using getters and setters for an ArrayList in Java? Here is what I have. I think I am using the getter correctly, but I don't know how to use a setter for an ArrayList.

private ArrayList<String> stringlist = new ArrayList<String>();
public ArrayList<String> getStringList() {
    return stringlist;
}

public ArrayList<String> setStringList() {
    // I don't know what to put here
    // I also don't know if my return value is correct
}

Solution

  • To set the value, you would take an ArrayList<String> passed as a parameter, and you would simply set the ArrayList to the parameter.

    Also, note the use of void rather than the ArrayList<String> shown in your question. Commonly, a setter method does not return anything.

    public void setStringList(ArrayList<String> stringList)
    {
        this.stringList = stringList;
    }