Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use System.arraycopy () and Arrays.copyOf () in Java

Shulou Source: shulou.com Published: 2022-06-01 11:47:56 09月30日 Update

This article mainly introduces "how to use System.arraycopy () and Arrays.copyOf () in Java". In daily operation, I believe many people have doubts about how to use System.arraycopy () and Arrays.copyOf () in Java. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use System.arraycopy () and Arrays.copyOf () in Java". Next, please follow the editor to study!

1. Simple code example

System.arraycopy ()

Int [] arr = {1, is the length to copy System.out.println 2, 3, 4, 5}; int [] copied = new int [10]; System.arraycopy (arr, 0, copied, 1, 5); / / 5 is the length to copy System.out.println (Arrays.toString (copied))

Output:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 1, 2, 3, 4, 5, 0, 0, 0, 0]

Arrays.copyOf ()

Int [] copied = Arrays.copyOf (arr, 10); / / 10 the the length of the new arraySystem.out.println (Arrays.toString (copied)); copied = Arrays.copyOf (arr, 3); System.out.println (Arrays.toString (copied))

Output:

[1, 2, 3, 4, 5, 0, 0, 0, 0, 0] [1, 2, 3] 2. Main differences

The difference is that Arrays.copyOf not only copies elements, it also creates a new array. System.arrayCopy is copied to an existing array.

If we read the source code of Arrays.copyOf (), we can see that it uses System.arraycopy ().

Public static int [] copyOf (int [] original, int newLength) {int [] copy = new int [newLength]; System.arraycopy (original, 0, copy, 0, Math.min (original.length, newLength)); return copy;} so far, the study on "how to use System.arraycopy () and Arrays.copyOf () in Java" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Tags: Learn array more help output different practical next code elements articles methods source code theory knowledge examples articles websites materials follow Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Xiaomi Docker Apple OPPO Reno