Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

I'm looking for a method in Java that will return a segment of an array. An example would be to get the byte array containing the 4th and 5th bytes of a byte array. I don't want to have to create a new byte array in the heap memory just to do that. Right now I have the following code:

doSomethingWithTwoBytes(byte[] twoByteArray);

void someMethod(byte[] bigArray)

{

      byte[] x = {bigArray[4], bigArray[5]};

      doSomethingWithTwoBytes(x);

}

I'd like to know if there was a way to just do doSomething(bigArray.getSubArray(4, 2)) where 4 is the offset and 2 is the length, for example.

1 Answer

0 votes
by (46k points)
Arrays.asList(myArray) delegates to new ArrayList(myArray), which doesn't copy the array but just stores the reference. Using List.subList(start, end) after that makes a SubList which just references the original list (which still just references the array). No copying of the array or its contents, just wrapper creation, and all lists involved are backed by the original array. (I thought it'd be heavier.)

Related questions

0 votes
1 answer
asked Oct 23, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Aug 29, 2019 in Java by Ritik (3.5k points)
0 votes
1 answer
0 votes
1 answer
asked Sep 11, 2019 in Java by Krishna (2.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...