ArrayList is a mutable container class, though, so you don't actually need a setter at all: simply have callers call getStringList() and then mutate the ArrayList themselves:

public final class DataHolder {
  private final ArrayList<String> stringList = new ArrayList<>();

  public ArrayList<String> getStringList() {
    return stringList;
  }
}

public static void main(String[] args) {
  DataHolder data = new DataHolder();
  data.getStringList().add("foo");
}

On the other hand, the more common requirement is to prevent callers from being able to mutate internal data structures, so that your class can actually enforce its invariants on its data. ArrayList is always mutable, so if you need to return an ArrayList but you don't want your private state to be modified, you'll need to copy:

public ArrayList<String> getStringList() {
  return new ArrayList<String>(stringList);
}

Alternatively, if possible, it's better to widen the return type and then return some other implementation that your class can use to enforce its invariants. For example, if you don't want people to modify your ArrayList using a getter method, you could widen the type from ArrayList<String> to List<String> and use an unmodifiable implementation, for example:

public List<String> getStringList() {
  return Collections.unmodifiableList(stringList);
}

On the other hand, for the setter, it depends on how you want to handle the values. Normally a setFoo method replaces the contents of foo, which you can of course do:

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

But most likely you want to also widen the type you will accept. For example, you could accept any Collection instead of just an ArrayList:

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

It may be more useful, however, to instead expose methods to mutate the underlying list in other ways. For example, perhaps you simply want to support adding new items to the list:

public void addString(String string) {
  this.stringList.add(string);
}

public void addStrings(Collection<String> strings) {
  this.stringList.addAll(strings);
}

If you do decide to expose a setter that replaces the value, you probably want to first check it for correctness. Since your class initializes the ArrayList in an instance initializer, most likely you don't expect it will ever be null. So you should throw an exception if it is:

public void setStringList(List<String> stringList) {
  if (stringList == null) {
    throw new NullPointerException("stringList must not be null");
  }
  this.stringList = stringList;
}

Java 7 added a new Objects.requireNonNull method for exactly this purpose.

Answer from Daniel Pryden on Stack Overflow
Top answer
1 of 5
60

ArrayList is a mutable container class, though, so you don't actually need a setter at all: simply have callers call getStringList() and then mutate the ArrayList themselves:

public final class DataHolder {
  private final ArrayList<String> stringList = new ArrayList<>();

  public ArrayList<String> getStringList() {
    return stringList;
  }
}

public static void main(String[] args) {
  DataHolder data = new DataHolder();
  data.getStringList().add("foo");
}

On the other hand, the more common requirement is to prevent callers from being able to mutate internal data structures, so that your class can actually enforce its invariants on its data. ArrayList is always mutable, so if you need to return an ArrayList but you don't want your private state to be modified, you'll need to copy:

public ArrayList<String> getStringList() {
  return new ArrayList<String>(stringList);
}

Alternatively, if possible, it's better to widen the return type and then return some other implementation that your class can use to enforce its invariants. For example, if you don't want people to modify your ArrayList using a getter method, you could widen the type from ArrayList<String> to List<String> and use an unmodifiable implementation, for example:

public List<String> getStringList() {
  return Collections.unmodifiableList(stringList);
}

On the other hand, for the setter, it depends on how you want to handle the values. Normally a setFoo method replaces the contents of foo, which you can of course do:

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

But most likely you want to also widen the type you will accept. For example, you could accept any Collection instead of just an ArrayList:

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

It may be more useful, however, to instead expose methods to mutate the underlying list in other ways. For example, perhaps you simply want to support adding new items to the list:

public void addString(String string) {
  this.stringList.add(string);
}

public void addStrings(Collection<String> strings) {
  this.stringList.addAll(strings);
}

If you do decide to expose a setter that replaces the value, you probably want to first check it for correctness. Since your class initializes the ArrayList in an instance initializer, most likely you don't expect it will ever be null. So you should throw an exception if it is:

public void setStringList(List<String> stringList) {
  if (stringList == null) {
    throw new NullPointerException("stringList must not be null");
  }
  this.stringList = stringList;
}

Java 7 added a new Objects.requireNonNull method for exactly this purpose.

2 of 5
5

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;
}
🌐
Quora
quora.com › What-are-the-getter-and-setter-methods-for-ArrayList-in-Java
What are the getter and setter methods for ArrayList in Java? - Quora
Answer (1 of 2): ArrayLists don’t have typical getters and setters. If you want to see the values of an ArrayList in Java, you can do one of several things. 1. Using iterators 2. 1. use get(int index) to inspect the value of each element 2. Use set(int index, Object o) to replace the value int ...
Top answer
1 of 7
11

Example -

import java.util.ArrayList;
import java.util.List;

public class Test {

List<String> list = null;

public List<String> getList() {
    return list;
}

public void setList(List<String> list) {
    this.list = list;
}

public static void main(String[] args) {
    Test test = new Test();
    List<String> sample = new ArrayList<String>();
    sample.add("element 1");
    test.setList(sample);
    List<String> sample1 = test.getList();
}
}
2 of 7
6

For better Encapsulation / OO design I would do following

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TestListGetterSetter {
List<String> list = new ArrayList<>();

//Return copy of the list
public List<String> getList() {
    return new ArrayList<>(list);
}

// Copy source list into destination list
public void setList(List<String> listToBeSet) {
    if (listToBeSet != null)
        this.list.addAll(listToBeSet);
}

public static void main(String[] args) {
    TestListGetterSetter testListGetterSetter = new TestListGetterSetter();

    List<String> clientList = new ArrayList<>(Arrays.asList("foo", "bar", "HiHa"));

    testListGetterSetter.setList(clientList);
    System.out.println("TestListGetterSetter.list before clientList modification = " + testListGetterSetter.getList());

    //Now you can change "clientList" without affecting testListGetterSetter object
    clientList.add("1");
    System.out.println("clientList modified List = " + clientList);
    System.out.println("TestListGetterSetter.list after clientList modification = " + testListGetterSetter.getList());
  }
}
🌐
CodingTechRoom
codingtechroom.com › question › getters-setters-arraylist-java
How to Implement Getters and Setters for ArrayLists in Java - CodingTechRoom
When working with ArrayLists, getters return the entire list while setters allow you to replace the list with a new one, or modify its contents directly through methods. ... // Example of an ArrayList with getters and setters public class FruitBasket { private ArrayList<String> fruits = new ...
🌐
YouTube
youtube.com › watch
ArrayList get and set methods Example in Java - YouTube
---------------------------------------------Like | share | Subscribe For More Free Videos-------------------------------------------------------------------...
Published: May 9, 2020
Find elsewhere
🌐
CodeJava
codejava.net › coding › java-getter-and-setter-tutorial-from-basics-to-best-practices
Java Getter and Setter Tutorial - from Basics to Best Practices
September 30, 2019 - And a getter is a method that reads value of a variable. Getter and setter are also known as accessor and mutator in Java.
🌐
Oracle
docs.oracle.com › cd › E19698-01 › 816-7609 › dynamic-16 › index.html
2.2.4 Bulk Getters and Setters
These methods rely on the classes shown in Table 2–2. Table 2–2 Bulk Getter and Setter Classes · The AttributeList class extends the java.util.ArrayList class.
🌐
JBoss.org
developer.jboss.org › thread › 110239
getter/setter for ArrayList embedded in HashMap| JBoss.org Content Archive (Read Only)
Original Post: I have getter/setter defined for properties, but still cannot send object of this class through WS, because the JBOSS generated WSDL doesn't include correct information for ArrayList. How can I correct this? package org.jboss.tutorial.webservice.bean; import java.util.*; import java.io.*; public class Something { private int a; private double b; private HashMap<String, ArrayList<String>> c; public Something() { a = 1; b = 2.0; c = new HashMap<String, ArrayList<String>>(); { ArrayList<String> arr = new ArrayList<String>(); arr.add("This is fun"); arr.add("Interesting"); arr.add("
🌐
YouTube
youtube.com › such code
Array List Methods (Java) - YouTube
A program that demonstrates some basic Array List methods, including add, remove, get, and set.
Published: July 6, 2015
Views: 5K
🌐
EDUCBA
educba.com › home › software development › software development tutorials › java tutorial › java getter setter
Java Getter Setter | Adding Setter and Getter Methods in Java
May 10, 2024 - Getters and Setters in java are two methods used for fetching and updating the value of a variable. Getter methods are concerned with fetching the updated value of a variable, while a setter method is used to set or update an existing variable’s ...
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
YouTube
youtube.com › codeash
ArrayList set() and get() method in Java | ArrayList set() method | ArrayList get() method - YouTube
🔰 ArrayList set() method :The set() method of java.util.ArrayList class is used to replace the element at the specified position in this list with the speci...
Published: March 9, 2023
Views: 430
🌐
Coderanch
coderanch.com › t › 682278 › java › Access-ArrayList-Getter-class
Access ArrayList Getter from inner class (Beginning Java forum at Coderanch)
July 18, 2017 - However after the analysis is done control is passed back to the GUI and if I call the getListGroupIDs method I am getting back an empty ArrayList. I assume this is because my Action Listener class is an inner class and the ArrayList is not available to it. I have tried everything I can think of (changing the ArrayList to Public, Private, blank) and nothing works. Here is where I declare my ArrayList and the setter/getter I created.