Array Slicing in JavaIn Java, array slicing is a way to get a subarray of the given array. Suppose, a[] is an array. It has 8 elements indexed from a[0] to a[7]. a[] = {8, 9, 4, 6, 0, 11, 45, 21} Now, we want to find a slice of the array index from a[3] to a[6]. Where a[3] is the startIndex and a[6] is the endIndex. Therefore, we get the following sliced array: a[] = {6, 0, 11, 45} In this section, we will learn how to find a slice of an array in Java. There are the following three ways to find a slice of an array:
Let's discuss each method in detail. By Copying ElementsIt is a native method for getting a slice of an array. In this method, first, we find the start and end index of the given array. After that, we create an empty array (sliced array) of size (endIndex - startIndex). From the given array, copy the elements (from startIndex) to the sliced array. At last, print the sliced array. Let's implement the above approach in a Java program to get a sliced array of the given array. In this program. we will use an array of primitive types. SliceArrayExample1.java Output: Slice of Array: [22, 45, 90, 67, 91, 0] By Using the copyOfRange() MethodThe 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 O(n) time to create slicing of an array and O(n) space to store elements, where n is the number of elements of the resulting array. Syntax: The method parses the three parameters:
It throws the following exceptions:
SliceArrayExample2.java Output: Slice of Array: [56, 90, 111, 901, 251] By Using Java 8 StreamBy using the following steps, we can find the slice of an array using the Java 8 Stream.
SliceArrayExample3.java Output: Slice of array for the specified range is: [100, 345, 897, 67, 123, 0] Next TopicFlutter vs Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India