Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java slice array as in python

Tags:

java

arrays

I have an byte array in Java and need to get parts of it. I wanted to work with Java arrays in the same way as I work with Python list, using slices. There is something similar to this in Java? Thank you in advance.

like image 697
daniboy000 Avatar asked Mar 11 '26 03:03

daniboy000


2 Answers

You can use Arrays' (https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/Arrays.html) built-in Arrays#copyOfRange()

Arrays.copyOfRange(oldArray, startIndex, endIndex);
like image 154
Alex Ciocan Avatar answered Mar 12 '26 16:03

Alex Ciocan


With plain arrays, no there is no equivalent.

With ArrayList, you can use array_list.subList(fromIndex, toIndex) to get a slice.

The slice is backed by the original ArrayList. Changes made to the slice will be reflected in the original. Non-structural changes made in the original will be reflected in the sublist; the results of structural modifications of the original list are undefined in the sublist.

byte[] byte_array = { 10, 20, 30, 40, 50 };
List<Byte> byte_list = Arrays.asList(byte_array);
List<Byte> slice = byte_list.subList(1,3); // {20, 30}

byte x = slice.get(1) ; // Returns 30

slice.set(0, 21);
// slice is now {21, 30} and byte_array is { 10, 21, 30, 40, 50}
like image 40
AJNeufeld Avatar answered Mar 12 '26 15:03

AJNeufeld



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!