[java] Offset an array ?

Started by
3 comments, last by cnstrnd 20 years, 1 month ago
My question may seem dumb, but is there a way to offset an array in java ? something like
int* ptr2 = ptr + offset 
in C++ ? I googled for a while but i didn't find anything on this subject ... I am probably dreaming now. Thanks [edited by - cnstrnd on March 18, 2004 11:19:53 AM]
Advertisement
You can''t do that with the build-in arrays. But you can make a small wrapper class for arrays that gives you the functionality that you want. See the java.lang.String implementation (array of characters) on how to do this. Your "offset" is the substring(int beginIndex) method.

Alternative: If you just want another array with the same elements,you can do this:
<YourClassName>[] offsetArray = new <YourClassName>[originalArray.length - offset];
System.arraycopy(originalArray, offset, offsetArray, 0, offsetArray.length);
I'll dig your first proposition. What I want exactly is to get access to a particular scanline in a 1D array of pixels from a BufferedImage : so the second method isn't interesting.

Thanks a lot for the tip.

--

EDIT: The substring method call the String(offset,count,[]value) constructor, thus references the original string. This is not practical for my purpose as I need fast access to the new array.
Right ?



[edited by - cnstrnd on March 18, 2004 3:33:10 PM]
If you plan to reuse the offsetable array in other parts of your application, then I would suggest using the wrapper class. The time /performance penalty to pay when calling the constructor is tiny. A little more annoying is the way you''ll have to do data access, using get and set methods. From the String analogy - charAt(int index)

If there is only one place that you want this (your case, image processing) just do:

for (int i=0; i < lineLength; i++)
imageArray[i+offset]
Yep, I''ll stick to this method. Thanks.

This topic is closed to new replies.

Advertisement