5

I refer to get only part of an Array in Java?, it use copyOfRange() method. So, i glanced at source code of this method. It copies the specified range of the specified array into a new array. I don't want to do this. I want to get a view of array.

Is there some ways to get this?

Community
  • 1
  • 1
vincent
  • 625
  • 1
  • 8
  • 20

1 Answers1

9

Refer to this answer from the same question that you referenced. Wrap the array with Arrays.asList() and use List.subList():

Integer[] a = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

List<Integer> view = Arrays.asList(a).subList(3, 6);

for (int i = 0; i < view.size(); i++)
    view.set(i, view.get(i) * 10);

System.out.println(view);
System.out.println(Arrays.toString(a));

prints:

[30, 40, 50]
[0, 1, 2, 30, 40, 50, 6, 7, 8, 9]

However, you won't be able to wrap arrays of primitive types without boxing the whole array first.

Community
  • 1
  • 1