copying array by value in java

前端 未结 5 907
轻奢々
轻奢々 2020-12-19 00:42

I tried to make an independent copy of an array but couldnt get one. see i cannot copy it integer by integer using a for loop because of efficiency reasons. Is there any oth

相关标签:
5条回答
  • 2020-12-19 00:56

    Arrays.copyOf() creates a new copy of an existing array (optionally with a different length).

    0 讨论(0)
  • 2020-12-19 01:01

    You can use System.arraycopy, but I doubt it will be much more efficient. The memory has to be copied anyways, so the only optimization possible is to copy bigger chunks of memory at once. But the size of a memory chunk copied at once is strongly limited by the processor/system-architecture.

    0 讨论(0)
  • 2020-12-19 01:05

    Check out System.arraycopy(). It can copy arrays of any type and is a preffered(and optimized) way to copy arrays.

    0 讨论(0)
  • 2020-12-19 01:15

    Try using clone () method for this purpose. As I remember this is the only case where Josh Bloch in Effective Java recommended to use cloning.

    int[] temp = arr.clone ();
    

    But arrayCopy is much faster. Sample performance test on array of 3,000,000 elements:

    System.arrayCopy time: 8ms
         arr.clone() time: 29ms
     Arrays.copyOf() time: 49ms
     simple for-loop time: 75ms
    
    0 讨论(0)
  • 2020-12-19 01:19

    Look at System.arraycopy() method. Like,

    int[] b = new int[a.length];
    System.arraycopy(a, 0, b, 0, a.length);
    
    0 讨论(0)
提交回复
热议问题