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

前端 未结 9 454
醉话见心
醉话见心 2020-11-29 16:02

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          


        
相关标签:
9条回答
  • 2020-11-29 16:29

    Using Apache ArrayUtils downloadable at this link you can easy use the method

    subarray(boolean[] array, int startIndexInclusive, int endIndexExclusive) 
    

    "boolean" is only an example, there are methods for all primitives java types

    0 讨论(0)
  • 2020-11-29 16:30

    Use copyOfRange method from java.util.Arrays class:

    int[] newArray = Arrays.copyOfRange(oldArray, startIndex, endIndex);

    For more details:

    Link to similar question

    0 讨论(0)
  • 2020-11-29 16:31

    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

    0 讨论(0)
  • 2020-11-29 16:31
    int newArrayLength = 30; 
    
    int[] newArray = new int[newArrayLength];
    
    System.arrayCopy(oldArray, 0, newArray, 0, newArray.length);
    
    0 讨论(0)
  • 2020-11-29 16:32

    Yes, it's called System.arraycopy(Object, int, Object, int, int) .

    It's still going to perform a loop somewhere though, unless this can get optimized into something like REP STOSW by the JIT (in which case the loop is inside the CPU).

    int[] src = new int[] {1, 2, 3, 4, 5};
    int[] dst = new int[3];
    
    System.arraycopy(src, 1, dst, 0, 3); // Copies 2, 3, 4 into dst
    
    0 讨论(0)
  • 2020-11-29 16:34

    I you are using java prior to version 1.6 use System.arraycopy() instead. Or upgrade your environment.

    0 讨论(0)
提交回复
热议问题