2

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?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Ilya
  • 55
  • 7

2 Answers2

6

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.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
1

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
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • This does not do the assignment in-place within `a`, as the python code does. Also, don't you think it's a bit overkill to make temporary copies and streams for everything? – Mad Physicist Jun 11 '19 at 19:14
  • @Mad Physicist do you have another idea? – Youcef LAIDANI Jun 11 '19 at 20:19
  • @Mad Physicist your solution is not complete it can fail in many cases, for that I create this generale solution, for your solution you can test with b = [1,2,3,4] and check what is the result – Youcef LAIDANI Jun 11 '19 at 20:31
  • As with Python, you have to use sensible inputs in Java. My snippet does not seek to be generic, it seeks to answer OP's question. – Mad Physicist Jun 11 '19 at 22:20