Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

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).

1 Answer

0 votes
by (46k points)

You must return a copy of your array.

public String[] getArr() {

  return arr == null ? null : Arrays.copyOf(arr, arr.length);

}

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...