Как скопировать массив в Java? Копирование массивов
В статье поговорим о некоторых методах копирования массивов в Java. Этот язык программирования имеет встроенные методы, предназначенные для решения данных задач. С их помощью вы сможете сделать как полную копию массива, так и выполнить копирование некоторых элементов массива.
Методы для копирования массивов в Java
В Java существует довольно много специальных методов для копирования массивов:
1.В первую очередь, хотелось бы упомянуть Object.clone() — этот метод вы можете использовать для полного копирования массива. Соответственно, если вы хотите скопировать массив частично, этот способ вам не подойдёт.
2.Следующий на очереди — System.arraycopy() — по сути, это один из наилучших способов создать частичную копию массива в Java. В этом методе определены следующие параметры: — массив, элементы которого планируем копировать; — индекс элемента; — итоговый (результирующий) массив; — первый элемент итогового массива; — общее число элементов, предназначенных для копирования.
К примеру, написав System.arraycopy(источник, 2, назначения, 5, 7), вы скопируете семь элементов из массива-источника в итоговый массив, начиная со второго индекса источника в пятый индекс результирующего массива.
3. Arrays.copyOf() — подойдёт вам, если планируете выполнить копирование нескольких первых элементов массива либо сделать полную копию массива. Способ не так универсален, как System.arraycopy() , но так же прост в применении.
4. Arrays.copyOfRange() — полезный метод, обеспечивающий частичное копирование массива.
В принципе, для решения большинства задач по полному либо частичному копированию массивов в Java вышеперечисленных методов вам вполне хватит. Только учтите, что методы, встроенные в Java для копирования, годятся лишь для одномерных массивов.
Пришла пора посмотреть на них в действии.
Теперь посмотрим на результат выполнения нашей программы:
Вот и всё. Если же вы хотите получить действительно продвинутые знания по Java, приходите на наш курс:
Скопируйте массив в Java
В этом посте будут обсуждаться различные способы создания копии массива в Java.
1. Использование System.arraycopy() метод
2. Использование Arrays.copyOf() метод
3. Использование Arrays.copyOfRange() метод
4. Использование Object.clone() метод
5. Использование Apache Commons Lang — ArrayUtils.clone() метод
Это все о копировании массива в Java.
Оценить этот пост
Средний рейтинг 5 /5. Подсчет голосов: 7
Голосов пока нет! Будьте первым, кто оценит этот пост.
Сожалеем, что этот пост не оказался для вас полезным!
Расскажите, как мы можем улучшить этот пост?
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования
Make copy of an array
I have an array a which is constantly being updated. Let’s say a = [1,2,3,4,5] . I need to make an exact duplicate copy of a and call it b . If a were to change to [6,7,8,9,10] , b should still be [1,2,3,4,5] . What is the best way to do this? I tried a for loop like:
but that doesn’t seem to work correctly. Please don’t use advanced terms like deep copy, etc., because I do not know what that means.
11 Answers 11
But, probably better to use clone() in most cases:
If you want to make a copy of:
This is the way to go:
Arrays.copyOf may be faster than a.clone() on small arrays. Both copy elements equally fast but clone() returns Object so the compiler has to insert an implicit cast to int[] . You can see it in the bytecode, something like this:
Java Array Copy Methods
Object.clone(): Object class provides clone() method and since array in java is also an Object, you can use this method to achieve full array copy. This method will not suit you if you want partial copy of the array.
System.arraycopy(): System class arraycopy() is the best way to do partial copy of an array. It provides you an easy way to specify the total number of elements to copy and the source and destination array index positions. For example System.arraycopy(source, 3, destination, 2, 5) will copy 5 elements from source to destination, beginning from 3rd index of source to 2nd index of destination.
Arrays.copyOf(): If you want to copy first few elements of an array or full copy of array, you can use this method. Obviously it’s not versatile like System.arraycopy() but it’s also not confusing and easy to use.
Arrays.copyOfRange(): If you want few elements of an array to be copied, where starting index is not 0, you can use this method to copy partial array.
I have a feeling that all of these «better ways to copy an array» are not really going to solve your problem.
I tried a for loop like [. ] but that doesn’t seem to be working correctly?
Looking at that loop, there’s no obvious reason for it not to work . unless:
- you somehow have the a and b arrays messed up (e.g. a and b refer to the same array), or
- your application is multi-threaded and different threads are reading and updating the a array simultaneously.
In either case, alternative ways of doing the copying won’t solve the underlying problem.
The fix for the first scenario is obvious. For the second scenario you will have to figure out some way of synchronizing the threads. Atomic array classes don’t help because they have no atomic copy constructors or clone methods, but synchronizing using a primitive mutex will do the trick.
(There are hints in your question that lead me to think that this is indeed thread related; e.g. your statement that a is constantly changing.)
You can try using Arrays.copyOf() in Java
![]()
All solution that call length from array, add your code redundant null checkersconsider example:
I recommend you not inventing the wheel and use utility class where all necessary checks have already performed. Consider ArrayUtils from apache commons. You code become shorter:
Apache commons you can find there
Example:
This method is similar to Arrays.copyOf , but it’s more flexible. Both of them use System.arraycopy under the hood.
See:
![]()
If you must work with raw arrays and not ArrayList then Arrays has what you need. If you look at the source code, these are the absolutely best ways to get a copy of an array. They do have a good bit of defensive programming because the System.arraycopy() method throws lots of unchecked exceptions if you feed it illogical parameters.
You can use either Arrays.copyOf() which will copy from the first to Nth element to the new shorter array.
Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values. For any indices that are valid in the copy but not the original, the copy will contain null. Such indices will exist if and only if the specified length is greater than that of the original array. The resulting array is of exactly the same class as the original array.
Class Arrays
The methods in this class all throw a NullPointerException , if the specified array reference is null, except where noted.
The documentation for the methods contained in this class includes brief descriptions of the implementations. Such descriptions should be regarded as implementation notes, rather than parts of the specification. Implementors should feel free to substitute other algorithms, so long as the specification itself is adhered to. (For example, the algorithm used by sort(Object[]) does not have to be a MergeSort, but it does have to be stable.)
This class is a member of the Java Collections Framework.
Method Summary
Methods declared in class java.lang.Object
Method Details
The < relation does not provide a total order on all float values: -0.0f == 0.0f is true and a Float.NaN value compares neither less than, greater than, nor equal to any value, even itself. This method uses the total order imposed by the method Float.compareTo(java.lang.Float) : -0.0f is treated as less than value 0.0f and Float.NaN is considered greater than any other value and all Float.NaN values are considered equal.
The < relation does not provide a total order on all float values: -0.0f == 0.0f is true and a Float.NaN value compares neither less than, greater than, nor equal to any value, even itself. This method uses the total order imposed by the method Float.compareTo(java.lang.Float) : -0.0f is treated as less than value 0.0f and Float.NaN is considered greater than any other value and all Float.NaN values are considered equal.
The < relation does not provide a total order on all double values: -0.0d == 0.0d is true and a Double.NaN value compares neither less than, greater than, nor equal to any value, even itself. This method uses the total order imposed by the method Double.compareTo(java.lang.Double) : -0.0d is treated as less than value 0.0d and Double.NaN is considered greater than any other value and all Double.NaN values are considered equal.
The < relation does not provide a total order on all double values: -0.0d == 0.0d is true and a Double.NaN value compares neither less than, greater than, nor equal to any value, even itself. This method uses the total order imposed by the method Double.compareTo(java.lang.Double) : -0.0d is treated as less than value 0.0d and Double.NaN is considered greater than any other value and all Double.NaN values are considered equal.
parallelSort
parallelSort
parallelSort
parallelSort
parallelSort
parallelSort
parallelSort
parallelSort
parallelSort
parallelSort
parallelSort
The < relation does not provide a total order on all float values: -0.0f == 0.0f is true and a Float.NaN value compares neither less than, greater than, nor equal to any value, even itself. This method uses the total order imposed by the method Float.compareTo(java.lang.Float) : -0.0f is treated as less than value 0.0f and Float.NaN is considered greater than any other value and all Float.NaN values are considered equal.
parallelSort
The < relation does not provide a total order on all float values: -0.0f == 0.0f is true and a Float.NaN value compares neither less than, greater than, nor equal to any value, even itself. This method uses the total order imposed by the method Float.compareTo(java.lang.Float) : -0.0f is treated as less than value 0.0f and Float.NaN is considered greater than any other value and all Float.NaN values are considered equal.
parallelSort
The < relation does not provide a total order on all double values: -0.0d == 0.0d is true and a Double.NaN value compares neither less than, greater than, nor equal to any value, even itself. This method uses the total order imposed by the method Double.compareTo(java.lang.Double) : -0.0d is treated as less than value 0.0d and Double.NaN is considered greater than any other value and all Double.NaN values are considered equal.
parallelSort
The < relation does not provide a total order on all double values: -0.0d == 0.0d is true and a Double.NaN value compares neither less than, greater than, nor equal to any value, even itself. This method uses the total order imposed by the method Double.compareTo(java.lang.Double) : -0.0d is treated as less than value 0.0d and Double.NaN is considered greater than any other value and all Double.NaN values are considered equal.
parallelSort
This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
parallelSort
This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
parallelSort
This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
parallelSort
This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
Implementation note: This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons. Temporary storage requirements vary from a small constant for nearly sorted input arrays to n/2 object references for randomly ordered input arrays.
The implementation takes equal advantage of ascending and descending order in its input array, and can take advantage of ascending and descending order in different parts of the same input array. It is well-suited to merging two or more sorted arrays: simply concatenate the arrays and sort the resulting array.
The implementation was adapted from Tim Peters’s list sort for Python ( TimSort). It uses techniques from Peter McIlroy’s «Optimistic Sorting and Information Theoretic Complexity», in Proceedings of the Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, January 1993.
This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
Implementation note: This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons. Temporary storage requirements vary from a small constant for nearly sorted input arrays to n/2 object references for randomly ordered input arrays.
The implementation takes equal advantage of ascending and descending order in its input array, and can take advantage of ascending and descending order in different parts of the same input array. It is well-suited to merging two or more sorted arrays: simply concatenate the arrays and sort the resulting array.
The implementation was adapted from Tim Peters’s list sort for Python ( TimSort). It uses techniques from Peter McIlroy’s «Optimistic Sorting and Information Theoretic Complexity», in Proceedings of the Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, January 1993.
This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
Implementation note: This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons. Temporary storage requirements vary from a small constant for nearly sorted input arrays to n/2 object references for randomly ordered input arrays.
The implementation takes equal advantage of ascending and descending order in its input array, and can take advantage of ascending and descending order in different parts of the same input array. It is well-suited to merging two or more sorted arrays: simply concatenate the arrays and sort the resulting array.
The implementation was adapted from Tim Peters’s list sort for Python ( TimSort). It uses techniques from Peter McIlroy’s «Optimistic Sorting and Information Theoretic Complexity», in Proceedings of the Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, January 1993.
This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
Implementation note: This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons. Temporary storage requirements vary from a small constant for nearly sorted input arrays to n/2 object references for randomly ordered input arrays.
The implementation takes equal advantage of ascending and descending order in its input array, and can take advantage of ascending and descending order in different parts of the same input array. It is well-suited to merging two or more sorted arrays: simply concatenate the arrays and sort the resulting array.
The implementation was adapted from Tim Peters’s list sort for Python ( TimSort). It uses techniques from Peter McIlroy’s «Optimistic Sorting and Information Theoretic Complexity», in Proceedings of the Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, January 1993.
parallelPrefix
parallelPrefix
parallelPrefix
parallelPrefix
parallelPrefix
Because floating-point operations may not be strictly associative, the returned result may not be identical to the value that would be obtained if the operation was performed sequentially.
parallelPrefix
parallelPrefix
parallelPrefix
binarySearch
binarySearch
binarySearch
binarySearch
binarySearch
binarySearch
binarySearch
binarySearch
binarySearch
binarySearch
binarySearch
binarySearch
binarySearch
binarySearch
binarySearch
binarySearch
binarySearch
binarySearch
equals
equals
Two arrays are considered equal if the number of elements covered by each range is the same, and all corresponding pairs of elements over the specified ranges in the two arrays are equal. In other words, two arrays are equal if they contain, over the specified ranges, the same elements in the same order.
equals
equals
Two arrays are considered equal if the number of elements covered by each range is the same, and all corresponding pairs of elements over the specified ranges in the two arrays are equal. In other words, two arrays are equal if they contain, over the specified ranges, the same elements in the same order.
equals
equals
Two arrays are considered equal if the number of elements covered by each range is the same, and all corresponding pairs of elements over the specified ranges in the two arrays are equal. In other words, two arrays are equal if they contain, over the specified ranges, the same elements in the same order.
equals
equals
Two arrays are considered equal if the number of elements covered by each range is the same, and all corresponding pairs of elements over the specified ranges in the two arrays are equal. In other words, two arrays are equal if they contain, over the specified ranges, the same elements in the same order.
equals
equals
Two arrays are considered equal if the number of elements covered by each range is the same, and all corresponding pairs of elements over the specified ranges in the two arrays are equal. In other words, two arrays are equal if they contain, over the specified ranges, the same elements in the same order.
equals
equals
Two arrays are considered equal if the number of elements covered by each range is the same, and all corresponding pairs of elements over the specified ranges in the two arrays are equal. In other words, two arrays are equal if they contain, over the specified ranges, the same elements in the same order.
equals
equals
Two arrays are considered equal if the number of elements covered by each range is the same, and all corresponding pairs of elements over the specified ranges in the two arrays are equal. In other words, two arrays are equal if they contain, over the specified ranges, the same elements in the same order.
Two doubles d1 and d2 are considered equal if: (Unlike the == operator, this method considers NaN equal to itself, and 0.0d unequal to -0.0d.)
equals
equals
Two arrays are considered equal if the number of elements covered by each range is the same, and all corresponding pairs of elements over the specified ranges in the two arrays are equal. In other words, two arrays are equal if they contain, over the specified ranges, the same elements in the same order.
Two floats f1 and f2 are considered equal if: (Unlike the == operator, this method considers NaN equal to itself, and 0.0f unequal to -0.0f.)
equals
equals
Two arrays are considered equal if the number of elements covered by each range is the same, and all corresponding pairs of elements over the specified ranges in the two arrays are equal. In other words, two arrays are equal if they contain, over the specified ranges, the same elements in the same order.
Two objects e1 and e2 are considered equal if Objects.equals(e1, e2) .
equals
Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, the two arrays are equal if they contain the same elements in the same order. Also, two array references are considered equal if both are null .
Two objects e1 and e2 are considered equal if, given the specified comparator, cmp.compare(e1, e2) == 0 .
equals
Two arrays are considered equal if the number of elements covered by each range is the same, and all corresponding pairs of elements over the specified ranges in the two arrays are equal. In other words, two arrays are equal if they contain, over the specified ranges, the same elements in the same order.
Two objects e1 and e2 are considered equal if, given the specified comparator, cmp.compare(e1, e2) == 0 .
copyOf
copyOf
copyOf
copyOf
copyOf
copyOf
copyOf
copyOf
copyOf
copyOf
copyOfRange
The resulting array is of exactly the same class as the original array.
copyOfRange
copyOfRange
copyOfRange
copyOfRange
copyOfRange
copyOfRange
copyOfRange
copyOfRange
copyOfRange
asList
The returned list implements the optional Collection methods, except those that would change the size of the returned list. Those methods leave the list unchanged and throw UnsupportedOperationException .
This method provides a way to wrap an existing array:
This method also provides a convenient way to create a fixed-size list initialized to contain several elements:
The list returned by this method is modifiable. To create an unmodifiable list, use Collections.unmodifiableList or Unmodifiable Lists.
hashCode
The value returned by this method is the same value that would be obtained by invoking the hashCode method on a List containing a sequence of Long instances representing the elements of a in the same order. If a is null , this method returns 0.
hashCode
The value returned by this method is the same value that would be obtained by invoking the hashCode method on a List containing a sequence of Integer instances representing the elements of a in the same order. If a is null , this method returns 0.
hashCode
The value returned by this method is the same value that would be obtained by invoking the hashCode method on a List containing a sequence of Short instances representing the elements of a in the same order. If a is null , this method returns 0.
hashCode
The value returned by this method is the same value that would be obtained by invoking the hashCode method on a List containing a sequence of Character instances representing the elements of a in the same order. If a is null , this method returns 0.
hashCode
The value returned by this method is the same value that would be obtained by invoking the hashCode method on a List containing a sequence of Byte instances representing the elements of a in the same order. If a is null , this method returns 0.
hashCode
The value returned by this method is the same value that would be obtained by invoking the hashCode method on a List containing a sequence of Boolean instances representing the elements of a in the same order. If a is null , this method returns 0.
hashCode
The value returned by this method is the same value that would be obtained by invoking the hashCode method on a List containing a sequence of Float instances representing the elements of a in the same order. If a is null , this method returns 0.
hashCode
The value returned by this method is the same value that would be obtained by invoking the hashCode method on a List containing a sequence of Double instances representing the elements of a in the same order. If a is null , this method returns 0.
hashCode
For any two arrays a and b such that Arrays.equals(a, b) , it is also the case that Arrays.hashCode(a) == Arrays.hashCode(b) .
The value returned by this method is equal to the value that would be returned by Arrays.asList(a).hashCode() , unless a is null , in which case 0 is returned.
deepHashCode
For any two arrays a and b such that Arrays.deepEquals(a, b) , it is also the case that Arrays.deepHashCode(a) == Arrays.deepHashCode(b) .
The computation of the value returned by this method is similar to that of the value returned by List.hashCode() on a list containing the same elements as a in the same order, with one difference: If an element e of a is itself an array, its hash code is computed not by calling e.hashCode() , but as by calling the appropriate overloading of Arrays.hashCode(e) if e is an array of a primitive type, or as by calling Arrays.deepHashCode(e) recursively if e is an array of a reference type. If a is null , this method returns 0.
deepEquals
Two array references are considered deeply equal if both are null , or if they refer to arrays that contain the same number of elements and all corresponding pairs of elements in the two arrays are deeply equal.
- e1 and e2 are both arrays of object reference types, and Arrays.deepEquals(e1, e2) would return true
- e1 and e2 are arrays of the same primitive type, and the appropriate overloading of Arrays.equals(e1, e2) would return true.
- e1 == e2
- e1.equals(e2) would return true.
If either of the specified arrays contain themselves as elements either directly or indirectly through one or more levels of arrays, the behavior of this method is undefined.
toString
toString
toString
toString
toString
toString
toString
toString
toString
The value returned by this method is equal to the value that would be returned by Arrays.asList(a).toString() , unless a is null , in which case «null» is returned.
deepToString
The string representation consists of a list of the array’s elements, enclosed in square brackets ( «[]» ). Adjacent elements are separated by the characters «, » (a comma followed by a space). Elements are converted to strings as by String.valueOf(Object) , unless they are themselves arrays.
If an element e is an array of a primitive type, it is converted to a string as by invoking the appropriate overloading of Arrays.toString(e) . If an element e is an array of a reference type, it is converted to a string as by invoking this method recursively.
To avoid infinite recursion, if the specified array contains itself as an element, or contains an indirect reference to itself through one or more levels of arrays, the self-reference is converted to the string «[. ]» . For example, an array containing only a reference to itself would be rendered as «[[. ]]» .
This method returns «null» if the specified array is null .
setAll
If the generator function throws an exception, it is relayed to the caller and the array is left in an indeterminate state.
parallelSetAll
If the generator function throws an exception, an unchecked exception is thrown from parallelSetAll and the array is left in an indeterminate state.
setAll
If the generator function throws an exception, it is relayed to the caller and the array is left in an indeterminate state.
parallelSetAll
If the generator function throws an exception, an unchecked exception is thrown from parallelSetAll and the array is left in an indeterminate state.
setAll
If the generator function throws an exception, it is relayed to the caller and the array is left in an indeterminate state.
parallelSetAll
If the generator function throws an exception, an unchecked exception is thrown from parallelSetAll and the array is left in an indeterminate state.
setAll
If the generator function throws an exception, it is relayed to the caller and the array is left in an indeterminate state.
parallelSetAll
If the generator function throws an exception, an unchecked exception is thrown from parallelSetAll and the array is left in an indeterminate state.