152. Introducing the sequence layout
In Problem 149, we already covered the ValueLayout
for basic data types. Next, let’s talk about the sequence layout (java.lang.foreign.SequenceLayout
).
But before introducing the sequence layout, let’s take a moment to analyze the following snippet of code:
try (Arena arena = Arena.ofConfined()) {
MemorySegment segment = arena.allocate(
ValueLayout.JAVA_DOUBLE.byteSize() * 10,
ValueLayout.JAVA_DOUBLE.byteAlignment());
for (int i = 0; i < 10; i++) {
segment.setAtIndex(ValueLayout.JAVA_DOUBLE,
i, Math.random());
}
for (int i = 0; i < 10; i++) {
System.out.printf("\nx = %.2f",
segment.getAtIndex(ValueLayout.JAVA_DOUBLE, i));
}
}
We start by creating a native memory segment for storing 10 double
values. Next, we rely on setAtIndex()
to set these double
values. Finally, we print them.
So, basically, we repeat the ValueLayout.JAVA_DOUBLE
10 times. When an element layout...