0

Hello StackExchange Community, I am noob with Java and want to index elements of an array MATLAB style. E.g., In MATLAB if I want to read the last 10 elements of an array I can type:

someArray = someOtherArray(end-10:end);

In Java, I can only think to use a for-loop, which seems rather inconvenient. Are there array methods in Java that do this? Should I write my own class and methods? Why or why not? Thanks, Kyle

P.S. I am actually trying to create a Processing sketch, but it seems Java rules of array usage have been inherited.

Strelok
  • 50,229
  • 9
  • 102
  • 115
wherestheforce
  • 527
  • 1
  • 5
  • 19
  • http://stackoverflow.com/questions/4439595/how-to-create-a-sub-array-from-another-array-in-java – kosa Aug 06 '12 at 04:44

3 Answers3

6
Arrays.copyOfRange(array, start, end) may help.
Sandeep Pathak
  • 10,567
  • 8
  • 45
  • 57
2

You can make a copy of your Array

someArray = Arrays.copyOfRange(someOtherArray,end-10, end);
christian.vogel
  • 2,117
  • 18
  • 22
1

Check out the ArrayUtils.subarray() method

Documentation: http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/ArrayUtils.html

Seth Nelson
  • 2,598
  • 4
  • 22
  • 29
  • 1
    As of Java 6, you can use `Arrays.copyOfRange(array, start, end)`. No need for a third-party package. – Ted Hopp Aug 06 '12 at 04:50