A multi-dimensional array is also a 1-dimensional array: int[a][b][c] is really just int[a*b*c], so the problem boils down to, how do you provide access safely? Simply like this:

public class Foo {
    private int[] array;

    public Foo(int[] array) {
        this.array = Arrays.copyOf(array, array.length);
    }

    /** @return a copy of the array */
    public int[] getArray() {
        return Arrays.copyOf(array, array.length);
    }
}

That's it.

Callers have a safe copy of the array and can use it in the full normal way arrays are used. No need for delegator methods.

Answer from Bohemian on Stack Overflow
🌐
Coderanch
coderanch.com › t › 610505 › java › Getter-Method-Array-Objects
Getter Method for Array Objects (Beginning Java forum at Coderanch)
When an array is created, all its elements are initially 0, false, or null, depending on the type of the array. So you either need to create Circles and put them into the array in your TheCircles constructor, or you need to do it separately after you create the TheCircles instance.
Discussions

Setter Getter Arrays Java - Stack Overflow
And also you have studentLecture ... both array and assign it. ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... Stack Overflow chat opening up to all users in January; Stack Exchange chat... ... Coming to a conclusion because of repeated historical evidence or are you faulty for assuming the ... More on stackoverflow.com
🌐 stackoverflow.com
Java array getters and setters.. help? | AnandTech Forums: Technology, Hardware, Software, and Deals
Yes, this is homework. No I'm not asking you to do it for me. But I'm stuck and need a nudge in the right direction. So how do I explain what's happening and keep it short and sweet....thinking........ I have a program where I am trying to use getter method to reference (in a sense, copy)... More on forums.anandtech.com
🌐 forums.anandtech.com
March 31, 2017
Using a getter to set the size of an array
Im a bit confused with the bike array. I assume you have another class called Bike that you are filling the array with? As for the getNum You dont need to use getNum() in the place to set the array. In your constructor, you set num when the object is created. num is a class variable, so all of your methods inside the class can access it. What you would instead use is: Bike[] bikeList = newBike[num]; Just a personal suggestion, but I would recommend renaming your variable to something more specific just to help readability, and instill good naming habits in the future as well. Something like numOfBikes is far easier to understand than just num. More on reddit.com
🌐 r/javahelp
3
2
April 25, 2019
java - Do I have to make getter setters for each element of an array? - Stack Overflow
My array is an array of objects. I only have one getter which returns the whole array. However, if I want to modify the fields of the array elements in another class, I cannot do it through the ar... More on stackoverflow.com
🌐 stackoverflow.com
March 30, 2020
🌐
YouTube
youtube.com › watch
Java Getters and Setters and Array of Object
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
🌐
Colorado State University
cs.colostate.edu › ~cs161 › Fall12 › labs › lab2 › libget.html
Library.java: Getters (Accessors)
public Book[] getBooks() { Book[] booksCopy = new Book[size]; for (int i = 0; i < size; i++) { booksCopy[i] = books[i]; } return booksCopy; } Note that we only copy the first size elements of books into a new array. This limits the user's view to the portion of storage that is actually holding books. This leads us to the next question: Why did we not do something similar for the Book class? The answer is due to the types of instance variables Book uses. First, int is a primitive type and returning it will always result in a copy. Second, while String is an object, and the getters will return a reference, the reference is safe.
🌐
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 ...
Find elsewhere
🌐
YouTube
youtube.com › sanjeet coder
#58 Java Encapsulation | Java Getter Setter and Constructor with Arrays | User Input - YouTube
Java Encapsulation | Java Getter Setter and Constructor with Arrays | User Input_____________________________________________________________________________...
Published: May 18, 2022
Views: 1K
🌐
Sololearn
sololearn.com › en › Discuss › 1880725 › getter-setter-and-array-of-object-in-java
Getter setter and array of object in java. | Sololearn: Learn to code for FREE!
But now I have some doubts to just write how you could do it because if you really mean an Object[] this will lead to 'problems' like reflections and should be avoided. Also you need to handle that arrays are static, in this context meaning: fixed size. I tend to recommend to use a List implementation whenever you need to deal with the limitations of an array.
🌐
DZone
dzone.com › data engineering › data › java getter and setter: basics, common mistakes, and best practices
Best Practices for Java Getter and Setter - DZone
October 1, 2019 - As you notice, the 2nd element of the array scores is modified outside the setter, in line 5. Because the getter method returns the reference of the internal variable scores directly, the outside code can obtain this reference and make a change to the internal object. A workaround for this case is that, instead of returning the reference directly in the getter, we should return a copy of the object.
🌐
AnandTech
forums.anandtech.com › home › software › programming
Java array getters and setters.. help? | AnandTech Forums: Technology, Hardware, Software, and Deals
March 31, 2017 - When I call the getter from within the main method (lets just say MainClass for simplicity), it works great and I can interact with the values from the array in "Class2". However, when I try to call the getter method from any other class (let's just say "Class3" for example), all the values from the array return as null.
🌐
Reddit
reddit.com › r/javahelp › using a getter to set the size of an array
r/javahelp on Reddit: Using a getter to set the size of an array
April 25, 2019 -

Hi, I'm a bit of a beginner to Java but am really enjoying it, it's my first OOP language.

I am doing an assignment where I have to create an array (can't be an array list) that's size is dependant on what the user allocated at the beginning. To do this, I've tried to use a setter and getter method. Unfortunately, when I'm testing my code, it looks like I haven't done it correctly because the array size is always 0. I've identified that it's taking the original declaration variable size rather than the size allocated by the setter.

private int num;
public BikeSystem(int num){
	setNum(num);
}

//getters`
public int getNum(){
	return num;
}

//setters
public void setNum(int num){
	this.num = num;
}

//Make ArrayList to store bikes
Bike [] bikeList = new Bike [getNum()];

If anyone could share their knowledge with me I would be super grateful.

Thank you so much.

🌐
DaniWeb
daniweb.com › programming › software-development › threads › 194609 › getter-setter-methods-for-string-arrays
java - getter/setter methods for String Arrays [SOLVED] | DaniWeb
May 29, 2009 - class Teacher extends Person { private final String[] subjectsTaught; private int subjectCount = 0; Teacher(String name, int capacity) { super(name); this.subjectsTaught = new String[capacity]; } public void addSubject(String value) { if (value == null) return; if (subjectCount == subjectsTaught.length) throw new IllegalStateException("Capacity reached"); subjectsTaught[subjectCount++] = value; } public String getSubjectsCsv() { return String.join(", ", java.util.Arrays.copyOf(subjectsTaught, subjectCount)); } } If you can use collections, a List<String> simplifies both sizing and formatting:
🌐
Stack Overflow
stackoverflow.com › questions › 60926293 › do-i-have-to-make-getter-setters-for-each-element-of-an-array
java - Do I have to make getter setters for each element of an array? - Stack Overflow
March 30, 2020 - However, if I want to modify the fields of the array elements in another class, I cannot do it through the array getter. The only solutions so far I have found is to either not leave the array field private or make getter/setter methods for each element of the array.
🌐
W3Schools
w3schools.com › java › ref_arraylist_get.asp
Java ArrayList get() Method
The get() method returns the item at a specified position in the list.
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;
}
🌐
W3Schools
w3schools.com › java › java_encapsulation.asp
Java Encapsulation and Getters and Setters
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users.
🌐
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 - Common mistakes when implementing getter and setter 5. Implementing getters and setters for primitive types 6. Implementing getters and setters for common object types 7. Implementing getters and setters for collection type 8. Implementing getters and setters for your own type · In Java, getter and setter are two conventional methods that are used for retrieving and updating value of a variable.The following code is an example of simple class with a private variable and a couple of getter/setter methods: