Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How does one create a subarray that shares memory with the original array in Java?

user-p17keMar 31 2023 — edited Mar 31 2023

In Julia, slicing operations like x[1:10] create a copy by default. However, copying data is not always the fastest option; in some cases, using a "view" into the parent array is more efficient. To address this, Julia provides functions and macros like view, @view, and @views for creating a "view" of a parent array, which is returned as a SubArray type. SubArray in Julia refers to the type of an array that shares memory with another array — that is, it's a container encoding a "view" of a parent AbstractArray. Here's an example:

julia> original_array = [10, 20, 30, 40, 50];

julia> sub_array = @view a[1:3];

julia> original_array
5-element Vector{Int64}:
 10
 20
 30
 40
 50

julia> sub_array
3-element view(::Vector{Int64}, 1:3) with eltype Int64:
 10
 20
 30

julia> sub_array[2] = 100;

julia> original_array
5-element Vector{Int64}:
  10
 100
  30
  40
  50

julia> sub_array
3-element view(::Vector{Int64}, 1:3) with eltype Int64:
  10
 100
  30

How does one achieve this in Java. I know of Arrays.copyRange, but it makes a new array. Making it less efficient, as well as not modifying the original array when the subarray is modified

This post has been answered by justsomeone on Mar 31 2023
Jump to Answer
Comments
Post Details
Added on Mar 31 2023
3 comments
493 views