Reputation: 43
Is there any way to get an ArrayList's inner array without having it being duplicated?
I have a function which takes a normal java array as input, which I want to call with the contents of an ArrayList. The problem is that I'm going to be calling it very frequently and making copies every time would cause performance issues.
Upvotes: 3
Views: 1883
Reputation: 7579
static Object[] getBackingArray(ArrayList<?> arrayList) {
try {
Field elementData = ArrayList.class.getDeclaredField("elementData");
elementData.setAccessible(true);
return (Object[]) elementData.get(arrayList);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
Note that you need to do this again each time the array list gets resized. Then again, this is brittle and awful and you should never do it in the first place.
If you need random access while processing your data, but the number of elements can grow and you can't put an upper bound on that, then ArrayList
is conceptually the right tool for the job. In that case, what you should do is refactor your processing code to work with Lists
. A random access implementation like ArrayList
gives you everything arrays do, so I don't see any problems with that in principle.
Upvotes: 3
Reputation: 15273
Write you own array list implementation with public access to the backing array, or use one from any existing Java Collections lib, for example ObjectArrayList<E>
from fastutil has method E[] elements()
. Yes, that's a bit odd to carry dependency for a single class, but if you are paying attention to performance, you could find primitive specializations of collections useful.
Upvotes: 2
Reputation: 8058
Not that I know of. However, there's nothing saying you can't create your own implementation of List which is wrapped around an exposed Array. Thread-safety and mutability -- and the fact that the association would be lost if further appends to the List forced it to reallocate the array -- would be issues you'd have to deal with, but there's no reason you couldn't make it work.
That's the nice thing about interfaces -- if one implementation doesn't have the characteristics you need, you can create another.
Upvotes: 1