Ilya
Ilya

Reputation: 55

Is there a way to assign array to slice of an array in Java

In Python one can get a view of a list and assign a different list to it. Is it possible in Java?

For example, in Python I would do

a = [1, 2, 3, 4, 5]
a[2:4] = [1, 1]

Is it possible to do something similar with a Java array?

Upvotes: 2

Views: 1048

Answers (2)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 60016

Here is a general solution to solve your issue of your problem :

public int[] setItemJavaCode(int[] a, int[] b, int startIndex, int endIndex) {
    int[] start = Arrays.copyOfRange(a, 0, startIndex);
    int[] end = Arrays.copyOfRange(a, endIndex, a.length);
    return IntStream.concat(
            Arrays.stream(start), IntStream.concat(Arrays.stream(b), Arrays.stream(end))
    ).toArray();
}

Explanation

a = [1, 2, 3, 4, 5]__> int[] a
a[2:4] = [1, 1]
  ^ ^    ^^^^^^______> int[] b
  | |
  | |________________> endIndex
  |__________________> startIndex

Upvotes: 1

Mad Physicist
Mad Physicist

Reputation: 114440

Yes and no. In Java, as in C, arrays are pieces of contiguous memory. If you want to write to them, you have to explicitly set the elements you are interested in. This usually means writing a loop. Python of course does the same thing, but it hides the loop so you don't have to write it out every time.

That being said, Java does have a method for hiding the loop when you copy segments from one array into another: System.arraycopy. So you can do something like

int[] a = new int[] {1, 2, 3, 4, 5};
int[] b = new int[] {1, 1};
System.arraycopy(b, 0, a, 2, 2);

A better approximation to the original might be

int[] a = new int[] {1, 2, 3, 4, 5};
System.arraycopy(new int[] {1, 1}, 0, a, 2, 2);

As an aside, the python notation a[2:4] = [1, 1] does not get a view and assign to it. It calls __setitem__ with a slice object on a. There is a big difference, especially for objects like lists that don't have views.

Upvotes: 6

Related Questions