2

Consider this class

class MyClass {
  private MyData[] data;

  public MyData[] getData() {
    return data == null ? null : (MyData[]) data.clone();
  }

This is creating issue

Security - Method returns internal array

Exposing internal arrays directly allows the user to modify some code that could be critical. It is safer to return a copy of the array.

Considering clone is bad and should be avoided, what can I do to make this code better?

daydreamer
  • 87,243
  • 191
  • 450
  • 722

2 Answers2

6

The easiest way to return a copy of the array would probably be by calling Arrays.copyOf:

public MyData[] getData() {
    return data == null ? null : Arrays.copyOf(data, data.length);
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • 1
    @sᴜʀᴇsʜᴀᴛᴛᴀ `Arrays#copyOf` uses `System.arraycopy` behind the scenes and this is easier to call/understand. – Luiggi Mendoza Oct 09 '15 at 20:40
2

I too agree that clone is bad but Not on Arrays. Clone performs well on array. Your code is clean .Keep it as it is.

Soon I'll attach the reference for Josh Bloch words on array clone.

Josh Bloch on Cloning

Doug Lea goes even further. He told me that he doesn't use clone anymore except to copy arrays. You should use clone to copy arrays, because that's generally the fastest way to do it. But Doug's types simply don't implement Cloneable anymore. He's given up on it. And I think that's not unreasonable.

If you completely avoid cloning, the next best option is

System.arraycopy(array1,0, array2, 0, array1.length);

because

Arrays.copyOf creates another array object internally and returns it where as System.arraycopy uses the passed array.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307