Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a sub array from another array in Java?

Tags:

java

arrays

How to create a sub-array from another array? Is there a method that takes the indexes from the first array such as:

methodName(object array, int start, int end) 

I don't want to go over making loops and making my program suffer.

I keep getting error:

cannot find symbol method copyOfRange(int[],int,int)

This is my code:

import java.util.*;  public class testing  {     public static void main(String [] arg)      {            int[] src = new int[] {1, 2, 3, 4, 5};          int b1[] = Arrays.copyOfRange(src, 0, 2);     } } 
like image 968
Gain Avatar asked Dec 14 '10 13:12

Gain


People also ask

How do you get a sub array from an array?

slice() The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified. Basically, slice lets you select a subarray from an array.

Are arrays copyOfRange inclusive?

copyOfRange(oldArray, startIndex, endIndex); startIndex is the initial index of the range to be copied, inclusive.


2 Answers

You can use

JDK > 1.5

Arrays.copyOfRange(Object[] src, int from, int to) 

Javadoc

JDK <= 1.5

System.arraycopy(Object[] src, int srcStartIndex, Object[] dest, int dstStartIndex, int lengthOfCopiedIndices);  

Javadoc

like image 111
jmj Avatar answered Oct 03 '22 02:10

jmj


Arrays.copyOfRange(..) was added in Java 1.6. So perhaps you don't have the latest version. If it's not possible to upgrade, look at System.arraycopy(..)

like image 43
Bozho Avatar answered Oct 03 '22 01:10

Bozho