Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I avoid .clone()?

Tags:

java

arrays

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?

like image 204
daydreamer Avatar asked Aug 09 '26 21:08

daydreamer


2 Answers

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);
}
like image 93
Mureinik Avatar answered Aug 11 '26 10:08

Mureinik


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.

like image 20
Suresh Atta Avatar answered Aug 11 '26 09:08

Suresh Atta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!