logo

Java의 배열 슬라이싱

자바에서는 배열 슬라이스 주어진 배열의 하위 배열을 얻는 방법입니다. a[]가 배열이라고 가정합니다. a[0]부터 a[7]까지 인덱스가 있는 8개의 요소가 있습니다.

a[] = {8, 9, 4, 6, 0, 11, 45, 21}

제나 아만 배우

이제 a[3]에서 a[6]까지의 배열 인덱스 조각을 찾고 싶습니다. 여기서 a[3]은 startIndex이고 a[6]은 endIndex입니다. 따라서 우리는 다음을 얻습니다. 슬라이스 배열 :

a[] = {6, 0, 11, 45}

이 섹션에서는 다음 내용을 학습합니다. Java에서 배열의 조각을 찾는 방법.

배열의 조각을 찾는 방법에는 다음 세 가지가 있습니다.

  • 요소를 복사하여
  • copyOfRange() 메서드를 사용하여
  • Java 8 스트림 사용

각 방법에 대해 자세히 논의해 보겠습니다.

자바 스윙 튜토리얼

요소 복사를 통해

배열의 조각을 가져오는 기본 방법입니다. 이 방법에서는 먼저 주어진 배열의 시작 및 끝 인덱스를 찾습니다. 그런 다음 크기가 빈 배열(슬라이스 배열)을 만듭니다. (endIndex - startIndex). 주어진 배열에서 (startIndex의) 요소를 슬라이스 배열로 복사합니다. 마지막으로 슬라이스 배열을 인쇄합니다.

위의 접근 방식을 다음과 같이 구현해 보겠습니다. 자바 주어진 배열의 분할된 배열을 얻는 프로그램입니다. 이 프로그램에서. 우리는 기본 유형의 배열을 사용할 것입니다.

SliceArrayExample1.java

 import java.util.Arrays; public class SliceArrayExample1 { //creating a functiion to the slice of an array public static int[] getSlice(int[] array, int startIndex, int endIndex) { // Get the slice of the Array int[] slicedArray = new int[endIndex - startIndex]; //copying array elements from the original array to the newly created sliced array for (int i = 0; i <slicedarray.length; i++) { slicedarray[i]="array[startIndex" + i]; } returns the slice of an array return slicedarray; main() method public static void main(string args[]) from which we will find int[] 56, 78, 22, 45, 90, 67, 91, 0, 31}; start index and end denotes part original to be int startindex="3," endindex="8;" get slicedarray="getSlice(array," startindex, 1); prints system.out.println('slice array: '+arrays.tostring(slicedarray)); < pre> <p> <strong>Output:</strong> </p> <pre> Slice of Array: [22, 45, 90, 67, 91, 0] </pre> <h2>By Using the copyOfRange() Method</h2> <p>The copyOfRange() method belongs to the Java Arrays class . It copies the specified range of the array to the newly created array (slice array) and returns the newly created array that contains the specified range from the original array. It takes <strong>O(n)</strong> time to create slicing of an array and <strong>O(n)</strong> space to store elements, where n is the number of elements of the resulting array.</p> <p> <strong>Syntax:</strong> </p> <pre> public static int[] copyOfRange(int[] original, int from, int to) </pre> <p>The method parses the three parameters:</p> <ul> <tr><td>original:</td> It is an array whose slice is to find. </tr><tr><td>from:</td> It is the start index. It must lie between 0 to the length of the given array. </tr><tr><td>to:</td> It is the end index. </tr></ul> <p>It throws the following exceptions:</p> <ul> <tr><td>ArrayIndexOutOfBoundsException:</td> If from is less than 0 or from is greater than the length of the specified array. </tr><tr><td>IllegalArgumentException:</td> If the parameter from is greater than to. </tr><tr><td>NullPointerException:</td> If the given array is null. </tr></ul> <p> <strong>SliceArrayExample2.java</strong> </p> <pre> import java.util.Arrays; public class SliceArrayExample2 { //function to get slice of a primitive array in Java public static int[] slice(int[] array, int startIndex, int endIndex) { // Get the slice of the Array int[] slicedArray = Arrays.copyOfRange(array, startIndex, endIndex); // return the slice return slicedArray; } public static void main(String args[]) { //get the array, startIndex and endIndex int[] array = {11, 23, 56, 90, 111, 901, 251, 800, 843}; int startIndex = 2, endIndex = 6; //get the slice of the array int[] sliceArray = slice(array, startIndex, endIndex + 1); //prints the slice of an array System.out.println(&apos;Slice of Array: &apos;+Arrays.toString(sliceArray)); } } </pre> <p> <strong>Output:</strong> </p> <pre> Slice of Array: [56, 90, 111, 901, 251] </pre> <h2>By Using Java 8 Stream</h2> <p>By using the following steps, we can find the slice of an array using the Java 8 Stream.</p> <ul> <li>First, find the startIndex and endIndex array.</li> <li>Convert the elements (that are in range) into Primitive Stream using range() method.</li> <li>Using the <strong>map()</strong> method map the specified elements from the specified array.</li> <li>By invoking the <strong>toArray()</strong> method, convert the mapped array into an array.</li> <li>Print the <strong>sliced</strong> </li> </ul> <p> <strong>SliceArrayExample3.java</strong> </p> <pre> import java.util.Arrays; import java.util.stream.IntStream; public class SliceArrayExample3 { //user defined function that finds the sslice of an specified array public static int[] findSlice(int[] array, int startIndex, int endIndex) { //getting the slice of an array and storing it in array slcarray[] //the range() method converts the elements into stream //getting the elments of the int stream using lambda expression //converting the mapped elements into sliced array using the toArray() method int[] slcarray = IntStream.range(startIndex, endIndex).map(i -&gt; array[i]).toArray(); //returns the slice of array return slcarray; } //main() method public static void main(String args[]) { //Get the array, startIndex and endIndex int[] array = {12, 45, 90, 55, 34, 100, 345, 897, 67, 123, 0, 789}; int startIndex = 5, endIndex = 10; //Get the slice of the array int[] slcarray = findSlice(array, startIndex, endIndex + 1); //Print the slice of the array System.out.println(&apos;Slice of array for the specified range is: &apos;+Arrays.toString(slcarray)); } } </pre> <p> <strong>Output:</strong> </p> <pre> Slice of array for the specified range is: [100, 345, 897, 67, 123, 0] </pre> <hr></slicedarray.length;>

copyOfRange() 메서드 사용

copyOfRange() 메소드는 Java Arrays 클래스에 속합니다. 배열의 지정된 범위를 새로 생성된 배열(슬라이스 배열)에 복사하고 원본 배열에서 지정된 범위를 포함하는 새로 생성된 배열을 반환합니다. 소요됩니다 에) 배열을 슬라이싱하는 데 걸리는 시간과 에) 요소를 저장할 공간. 여기서 n은 결과 배열의 요소 수입니다.

자바 대 C++

통사론:

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

이 메서드는 세 가지 매개변수를 구문 분석합니다.

    원래의:슬라이스를 찾을 배열입니다.에서:시작 인덱스입니다. 0에서 주어진 배열의 길이 사이에 있어야 합니다.에게:종료지수입니다.

다음과 같은 예외가 발생합니다.

    ArrayIndexOutOfBounds예외:from이 0보다 작거나 from이 지정된 배열의 길이보다 큰 경우.IllegalArgumentException:매개변수 from이 to보다 큰 경우.NullPointer예외:주어진 배열이 null인 경우.

SliceArrayExample2.java

 import java.util.Arrays; public class SliceArrayExample2 { //function to get slice of a primitive array in Java public static int[] slice(int[] array, int startIndex, int endIndex) { // Get the slice of the Array int[] slicedArray = Arrays.copyOfRange(array, startIndex, endIndex); // return the slice return slicedArray; } public static void main(String args[]) { //get the array, startIndex and endIndex int[] array = {11, 23, 56, 90, 111, 901, 251, 800, 843}; int startIndex = 2, endIndex = 6; //get the slice of the array int[] sliceArray = slice(array, startIndex, endIndex + 1); //prints the slice of an array System.out.println(&apos;Slice of Array: &apos;+Arrays.toString(sliceArray)); } } 

산출:

자바에서 문자열 배열 생성
 Slice of Array: [56, 90, 111, 901, 251] 

Java 8 스트림을 사용하여

다음 단계를 사용하면 Java 8 Stream을 사용하여 배열 조각을 찾을 수 있습니다.

  • 먼저 startIndex 및 endIndex 배열을 찾습니다.
  • range() 메소드를 사용하여 (범위 내에 있는) 요소를 Primitive Stream으로 변환합니다.
  • 사용하여 지도() 메소드는 지정된 배열에서 지정된 요소를 매핑합니다.
  • 호출함으로써 toArray() 메서드를 사용하여 매핑된 배열을 배열로 변환합니다.
  • 인쇄 슬라이스

SliceArrayExample3.java

 import java.util.Arrays; import java.util.stream.IntStream; public class SliceArrayExample3 { //user defined function that finds the sslice of an specified array public static int[] findSlice(int[] array, int startIndex, int endIndex) { //getting the slice of an array and storing it in array slcarray[] //the range() method converts the elements into stream //getting the elments of the int stream using lambda expression //converting the mapped elements into sliced array using the toArray() method int[] slcarray = IntStream.range(startIndex, endIndex).map(i -&gt; array[i]).toArray(); //returns the slice of array return slcarray; } //main() method public static void main(String args[]) { //Get the array, startIndex and endIndex int[] array = {12, 45, 90, 55, 34, 100, 345, 897, 67, 123, 0, 789}; int startIndex = 5, endIndex = 10; //Get the slice of the array int[] slcarray = findSlice(array, startIndex, endIndex + 1); //Print the slice of the array System.out.println(&apos;Slice of array for the specified range is: &apos;+Arrays.toString(slcarray)); } } 

산출:

 Slice of array for the specified range is: [100, 345, 897, 67, 123, 0]