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

前端 未结 9 455
醉话见心
醉话见心 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:42

    The code is correct so I'm guessing that you are using an older JDK. The javadoc for that method says it has been there since 1.6. At the command line type:

    java -version
    

    I'm guessing that you are not running 1.6

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

    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(..)

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

    JDK >= 1.8

    I agree with all the answers above. There is also a nice way with Java 8 Streams:

    int[] subArr = IntStream.range(startInclusive, endExclusive)
                            .map(i -> src[i])
                            .toArray();
    

    The benefit about this is, it can be useful for many different types of "src" array and helps to improve writing pipeline operations on the stream.

    Not particular about this question, but for example, if the source array was double[] and we wanted to take average() of the sub-array:

    double avg = IntStream.range(startInclusive, endExclusive)
                        .mapToDouble(index -> src[index])
                        .average()
                        .getAsDouble();
    
    0 讨论(0)
提交回复
热议问题