Получить часть массива java

Как получить подмассив массива в Java, не копируя данные?

У меня есть библиотека классов, работающая с моими данными, которая считывается в буфер. Возможно ли как-то избежать повторного копирования массивов, передавая части данных глубже и глубже в методы обработки? Ну, это звучит странно, но в моем конкретном случае есть специальный писатель, который делит данные на блоки и записывает их индивидуально в разные местоположения, поэтому он просто выполняет System.arraycopy, получает то, что ему нужно, и называет лежащего в основе автора, с этим новым sub. И это случается много раз. Каков наилучший подход для реорганизации такого кода?

7 ответов

Многие классы в Java принимают подмножество массивов в качестве параметра. Например. Writer.write(char cbuf [], int off, int len). Возможно, этого уже достаточно для вашего использования.

Arrays.asList(array).subList(x, y). 

Этот метод не дает вам массив, но List , который намного более гибкий.

Возвращает список фиксированного размера, поддерживаемый указанным массивом. Я принимаю твои извинения.

Чтобы исправить себя, он не работает с примитивными типами: Arrays.asList(new int[]<. >) имеет тип List ( поэтому не то, что я хотел).

Нет реального способа переносить любые данные без копирования и получения реального arra y в Java. Вы просто не можете создать новый массив поверх существующей памяти. У вас есть в основном 2 варианта:

  • Используйте методы, которые могут принимать диапазон массива. Это было уже рекомендовано.
  • Используйте оболочку, которая дает некоторую абстракцию, близкую к массиву, и подходит для многих приложений. Ниже будет описано ниже.

Вы можете использовать иерархию классов java.nio.Buffer , особенно java.nio.ByteBuffer , которая предлагает абстракцию буфера для всего массива или поддиапазонов. Часто это то, что нужно людям. Это также предлагает много интересных возможностей, таких как отображение «нулевой копии» и гибкое представление байтовой области.

Вот пример обертывания с помощью java.nio.ByteBuffer . Это должно быть очень близко к тому, что вам нужно. По крайней мере, для некоторых операций.

byte [] a1 = ; ByteBuffer buf = ByteBuffer.wrap(a1,1,2); 

Затем вы можете выполнить buf любую операцию ByteBuffer .

Просто предупреждение, buf.array() возвращает исходный массив a1 (бэкэнд) со всеми элементами.

Читайте также:  Prompt в javascript команда

И так, даже если я сделаю buf = ByteBuffer.wrap (a1, 1, 2) . buf.array () все равно вернет <0, 0, 1, 0>. Таким образом, эта идея не может быть использована для получения подмассива?

Вы просто не можете получить настоящий под-массив без копирования в Java. Так что обертки используются. Первый список был проиллюстрирован ранее, а буферная абстракция — еще одна. Я бы сказал, что это гораздо более полезно в диапазоне байтов памяти, но для сложных объектных массивов список более распространен.

Источник

How to Split an Array in Java

Learn to split an array in Java using different ways. We will learn to split the array into equal parts, at the specified index and of equal lengths.

The copyOfRange() creates a new array of the same type as the original array, and contains the items of the specified range of the original array into a new array. Note that this method internally uses System.arraycopy() to copy the array items.

public static T[] copyOfRange(T[] original, int from, int to)

These are the method parameters.

  • original – the array from which a range is to be copied
  • from – the initial index of the range to be copied, inclusive
  • to – the final index of the range to be copied, exclusive. (This index may lie outside the array.)

An important point to note is that to index may lie outside the length of the array. Such index locations are filled with the default value of the type of array.

For example, for int , long and double types, the additional indices will be filled with zeros. For a boolean array, such indices will be filled with false and for object arrays, such positions will be filled with null.

It will throw IllegalArgumentException if from is bigger than to .

Читайте также:  Алгоритм форда фалкерсона java

2. Splitting Array at Specified Index

Let’s say we are dividing an array in such a way that we should get two arrays of defined lengths. In such a case, we must use the copyOfRange() API to create two new arrays from the original array.

The first new array will be having the items starting from zero to the specified index, and the second new array will have items from the specified index to the end of the original array.

int[] original = ; int givenIndex = 3; splitArrayPart1 = Arrays.copyOfRange(original, 0, givenIndex); splitArrayPart2 = Arrays.copyOfRange(original, givenIndex, original.length); System.out.println(Arrays.toString(splitArrayPart1)); //[0, 1, 2] System.out.println(Arrays.toString(splitArrayPart2)); //[3, 4, 5, 6, 7, 8, 9]

2. Splitting Array in Two Equal Parts

Splitting the array in half is very much similar to the first example. We only have to find the split position ourselves and that is the middle of the array.

int[] original = ; int splitSize = original.length / 2; int[] splitArrayPart1 = Arrays.copyOfRange(original, 0, splitSize); int[] splitArrayPart2 = Arrays.copyOfRange(original, splitSize, original.length); System.out.println(Arrays.toString(splitArrayPart1)); //[0, 1, 2, 3, 4] System.out.println(Arrays.toString(splitArrayPart2)); //[5, 6, 7, 8, 9]

3. Splitting Array into N Parts

This is a bit tricky. Here we have to iterate over the array length but in chunks of a specified number. Then we have to use copyOfRange() method to create new array instances from those copied items.

We must keep special attention if there are remaining items after splitting the array equally. We need to create a new array of these remainder items.

For example, our original array contains 10 items. If we try to split the array in such a way that any new array must not contain more than 3 items. So in this case, there will be 4 arrays after the splitting procedure. 3 Arrays will have 3 items each, and 4th array will have only one item.

The given below is a method that does all the work described above.

public static List splitArray(T[] array, int splitSize) < int numberOfArrays = array.length / splitSize; int remainder = array.length % splitSize; int start = 0; int end = 0; Listlist = new ArrayList(); for (int i = 0; i < numberOfArrays; i++) < end += splitSize; list.add(Arrays.copyOfRange(array, start, end)); start = end; >if(remainder > 0) < list.add(Arrays.copyOfRange(array, start, (start + remainder))); >return list; >

Let us test this method with our original array and divide such that there must be at most 3 items in an array.

List arrayParts = splitArray(ArrayUtils.toObject(original), 3); for(Integer[] o: arrayParts) < System.out.println(Arrays.toString(o)); >//Output [0, 1, 2] [3, 4, 5] [6, 7, 8] [9]

In this tutorial, we learned to split an array in Java for different usecases. We learned to use the Arrays.copyOfRange() API to split the arrays into any number of parts.

There are other ways for array splitting as well, such that converting the array to List and the split the list. Such methods create unnecessary temporary variables without giving any clear advantage.

Источник

Получить подмассив массива между определенным индексом в Java

В этом посте мы обсудим несколько методов получения подмассива непримитивного массива между указанными индексами в Java.

1. Использование Arrays.copyOfRange() метод

Стандартный способ получить подмассив массива — использовать Arrays.copyOfRange() , который возвращает подмассив, содержащий указанный диапазон из исходного массива, как показано ниже:

результат:

[B, C, D, E]

2. Использование Java 8

Мы можем использовать Java Stream, представленный в Java SE 8, для получения подмассива из массива. Идея состоит в том, чтобы получить поток элементов между указанным диапазоном, а затем вызвать метод toArray() метод для накопления элементов потока в новый массив.

результат:

[B, C, D, E]

3. Использование System.arraycopy() метод

System.arraycopy() Метод также можно использовать для получения копии из указанной позиции исходного массива в указанную позицию целевого массива.

результат:

[B, C, D, E]

4. Преобразование в список

Здесь идея состоит в том, чтобы преобразовать массив в список и использовать subList() метод для получения элементов между желаемым диапазоном. Затем мы используем toArray(T[]) метод для копирования списка во вновь выделенный массив.

Обратите внимание, что этот метод фактически не копирует массив. И результирующий список, и подсписок поддерживаются исходным массивом и просто ссылаются на массив.

Источник

Оцените статью