168

Imagine that I have this class:

public class Test
{
  private String[] arr = new String[]{"1","2"};    

  public String[] getArr() 
  {
    return arr;
  }
}

Now, I have another class that uses the above class:

Test test = new Test();
test.getArr()[0] ="some value!"; //!!!

So this is the problem: I have accessed a private field of a class from outside! How can I prevent this? I mean how can I make this array immutable? Does this mean that with every getter method you can work your way up to access the private field? (I don't want any libraries such as Guava. I just need to know the right way to do this).

8
  • 10
    Actually, making it final does prevent the modification of the field. However, preventing the modification of the Object referred to by a field is more complicated. Commented Feb 11, 2013 at 9:42
  • 22
    There's a problem with your mental model if you think being able to modify an array to which you have a reference stored in a private field is the same as being able to modify a private field.
    – Joren
    Commented Feb 11, 2013 at 10:18
  • 46
    If it's private, why expose it in the first place? Commented Feb 11, 2013 at 13:59
  • 7
    It took me a while to figure this out but it always improves my code when I ensure that all data structures are completely encapsulated within their object--meaning there is no way to "Get" your "arr", instead do whever you must inside the class or provide an iterator.
    – Bill K
    Commented Feb 11, 2013 at 21:23
  • 9
    Is anyone else also surprised why this question got so much attention?
    – Roman
    Commented Feb 26, 2013 at 11:35

11 Answers 11

382

If you can use a List instead of an array, Collections provides an unmodifiable list:

public List<String> getList() {
    return Collections.unmodifiableList(list);
}
3
  • Added an answer that uses Collections.unmodifiableList(list) as assignment to the field, to make sure that the list isn't changed by the class itself. Commented Jul 29, 2014 at 1:44
  • Just wondering, If you decompile this method you get a lot of new keywords. Doesn't this hurt the performance when getList() get access a lot. For example in render code.
    – Thomas15v
    Commented Dec 15, 2014 at 7:52
  • 2
    Note that this works if the elements of the arrays are immutable in themselves like String is, but if they are mutable something might have to be done to prevent the caller from changing them.
    – Lii
    Commented Feb 19, 2015 at 10:48
165

You must return a copy of your array.

public String[] getArr() {
  return arr == null ? null : Arrays.copyOf(arr, arr.length);
}
13
  • 123
    I would like to remind people that although this has been voted the correct answer to the question, the best solution to the problem is actually as sp00m says - to return an Unmodifiable List. Commented Feb 11, 2013 at 12:10
  • 48
    Not if you actually need to return an array.
    – Svish
    Commented Feb 11, 2013 at 12:13
  • 8
    Actually, the best solution to the problem discussed is often as @MikhailVladimirov says: - to provide or return a view of the array or collection. Commented Feb 11, 2013 at 12:27
  • 20
    but do make sure it's a deep copy, not a shallow copy, of the data. For Strings it makes no difference, for other classes like Date where the content of the instance can be modified it can make a difference.
    – jwenting
    Commented Feb 11, 2013 at 13:47
  • 16
    @Svish I should’ve been more drastic: if you return an array from an API function you’re doing it wrong. In private functions inside a library it might be right. In an API (where protection against modifiability plays a role), it never is. Commented Feb 11, 2013 at 14:42
45

Modifier private protects only field itself from being accessed from other classes, but not the object references by this field. If you need to protect referenced object, just do not give it out. Change

public String [] getArr ()
{
    return arr;
}

to:

public String [] getArr ()
{
    return arr.clone ();
}

or to

public int getArrLength ()
{
    return arr.length;
}

public String getArrElementAt (int index)
{
    return arr [index];
}
1
  • 5
    This article does not argue against using clone on arrays, only on objects that can be subclassed. Commented Feb 24, 2013 at 17:16
28

The Collections.unmodifiableList has already been mentioned - the Arrays.asList() strangely not! My solution would also be to use the list from the outside and wrap the array as follows:

String[] arr = new String[]{"1", "2"}; 
public List<String> getList() {
    return Collections.unmodifiableList(Arrays.asList(arr));
}

The problem with copying the array is: if you're doing it every time you access the code and the array is big, you'll create a lot of work for the garbage collector for sure. So the copy is a simple but really bad approach - I'd say "cheap", but memory-expensive! Especially when you're having more than just 2 elements.

If you look at the source code of Arrays.asList and Collections.unmodifiableList there is actually not much created. The first just wraps the array without copying it, the second just wraps the list, making changes to it unavailable.

2
  • You make the assumption here that the array including the strings is copied each time. It isn't, only the references to the immutable strings are copied. As long as your array is not huge, the overhead is negligible. If the array is huge, go for lists and immutableList all the way! Commented Jul 29, 2014 at 1:10
  • No, I didn't make that assumption - where? It is about the references that are copied - doesn't matter if it is a String or any other object. Just saying that for big arrays I wouldn't recommend copying the array and that the Arrays.asList and Collections.unmodifiableList operations are probably cheaper for bigger arrays. Maybe someone can calculate how many elements are necessary, but I've already seen code in for-loops with arrays containing thousands of elements being copied just to prevent modification - that's insane!
    – michael_s
    Commented Jul 30, 2014 at 6:23
6

You can also use ImmutableList which should be better than the standard unmodifiableList. The class is part of Guava libraries that was create by Google.

Here is the description:

Unlike Collections.unmodifiableList(java.util.List), which is a view of a separate collection that can still change, an instance of ImmutableList contains its own private data and will never change

Here is a simple example of how to use it:

public class Test
{
  private String[] arr = new String[]{"1","2"};    

  public ImmutableList<String> getArr() 
  {
    return ImmutableList.copyOf(arr);
  }
}
1
  • Use this solution if you cannot trust the Test class to leave the returned list unaltered. You need to make sure that ImmutableList is returned, and that the elements of the list are immutable as well. Otherwise my solution should be safe as well. Commented Jul 29, 2014 at 2:03
3

at this point of view you should use system array copy:

public String[] getArr() {
   if (arr != null) {
      String[] arrcpy = new String[arr.length];
      System.arraycopy(arr, 0, arrcpy, 0, arr.length);
      return arrcpy;
   } else
      return null;
   }
}
1
  • -1 as it doesn't do anything over calling clone, and is not as concise. Commented Jul 29, 2014 at 1:16
2

You could return a copy of the data. The caller who chooses to change the data will only be changing the copy

public class Test {
    private static String[] arr = new String[] { "1", "2" };

    public String[] getArr() {

        String[] b = new String[arr.length];

        System.arraycopy(arr, 0, b, 0, arr.length);

        return b;
    }
}
2

The nub of the problem is that you are returning a pointer to a mutable object. Oops. Either you render the object immutable (the unmodifiable list solution) or you return a copy of the object.

As a general matter, finality of objects does not protect objects from being changed if they are mutable. These two problems are "kissing cousins."

1
  • Well Java has references, while C has pointers. Enough said. Further, the "final" modifier can have multiple impacts depending on where it is applied. Applying on a class member will enforce you to only assign value to the member exactly once with the "=" (assignment) operator. This has nothing to do with immutability. If you replace the reference of a member to a new one (some other instance from the same class), the previous instance will remain unchanged (but may be GCed if no other references are holding them). Commented Feb 13, 2013 at 10:17
1

Returning an unmodifiable list is a good idea. But a list that is made unmodifiable during the call to the getter method can still be changed by the class, or classes that are derived from the class.

Instead you should make it clear to anybody that extends the class that the list should not be modified.

So in your example it could lead to the following code:

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Test {
    public static final List<String> STRINGS =
        Collections.unmodifiableList(
            Arrays.asList("1", "2"));

    public final List<String> getStrings() {
        return STRINGS;
    }
}

In the above example I've made the STRINGS field public, in principle you could do away with the method call, as the values are already known.

You could also assign the strings to a private final List<String> field made unmodifiable during construction of the class instance. Using a constant or instantiation arguments (of the constructor) depends on the design of the class.

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Test {
    private final List<String> strings;

    public Test(final String ... strings) {
        this.strings = Collections.unmodifiableList(Arrays
                .asList(strings));
    }

    public final List<String> getStrings() {
        return strings;
    }
}
0

Since Java 9, an immutable list can also be constructed from a static factory method List.of() which results in just a bit fewer imports and code:

With an alias being returned from getUsers() when the original users fields can be modified:

class Computer {
    private String[] users = new String[] {"user1", "user2", "user3"};
    public String[] getUsers;

    String[] getUsers() {
        return this.users;
    }
}

Computer c = new Computer();
c.getUsers()[0] = "me";
for (String user: c.getUsers()) {
    System.out.println(user);
}

Output:

me
user2
user3

Using the immutable list:

import java.util.List;

class Computer {
    private String[] users = new String[] {"user1", "user2", "user3"};
    public List<String> getUsers;

    List<String> getUsers() {
        return List.of(this.users);
    }
}

Computer c = new Computer();
c.getUsers().set(0, "me");
for (String user: c.getUsers()) {
    System.out.println(user);
}

Output:

user1
user2
user3
0

Yes, you should return a copy of the array:

public String[] getArr()
{
    return Arrays.copyOf(arr);
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.