1

Let's say I've an array:

int[] array = new int[] {0,1,2,3,4,5,6,7,8,9};

I want to print a sub-array of the above array starting from index i and ending at index j. For example, if i=3 & j=6, the sub-array to be printed would be:
[3, 4, 5, 6] or simply as 3 4 5 6

We can simply print the sub-array with a for loop as:

for (int k=i; k<=j; k++) System.out.print(array[k]+" ");

But I'm looking for a method to achieve this like Arrays toString() method.
So, we can use Arrays.copyOfRange() to create a copy of the desired sub-array and print it as:

int[] subArray1 = Arrays.copyOfRange(array, i, j+1);
System.out.println(Arrays.toString(subArray1));

There are few other ways to achieve this as well but all of them tend to use extra space to create a copy of the sub-array. Is there any method or way (except the above) to directly print the sub-arrays from the given indices without using extra memory?

Olivier
  • 13,283
  • 1
  • 8
  • 24
GURU Shreyansh
  • 881
  • 1
  • 7
  • 19
  • 1
    Any method you would find would probably do it using one of the methods you stated and would have the same limitations. I might consider using a List and using the `subList` feature. – WJS Jul 04 '21 at 12:55
  • 1
    you can just copy the source code of `Arrays.toString` and introduce start and end indices as parameters. Or what else is so special about `Arrays.toString`? – f1sh Jul 04 '21 at 13:00
  • 2
    `Arrays.toString()` just uses a `StringBuilder` internally and a for-loop which adds each element to the builder and then returns the string with `toString()` when done. – Matt Jul 04 '21 at 13:17
  • @f1sh I never mentioned that I want a method exactly the same as `Arrays.toString()`, any method that can achieve the above is fine for me. – GURU Shreyansh Jul 04 '21 at 13:18
  • 1
    Method `Arrays.toString` also uses extra memory: a string builder to append the contents of the _entire_ input array and then creating a string. If you need just to print the contents of the array between the two indexes, you should create your own utility class using `for` loop or streams. – Nowhere Man Jul 04 '21 at 13:20
  • do check this question https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array – Ashish Mishra Jul 04 '21 at 15:17

0 Answers0