ArrayList’s Iterator class ArrayList.Itr is private, so I can’t subclass that guy.
The things ArrayList.Itr access in ArrayList are private, so I cannot provide my own implementation.
The only way I can see how to do this is to subclass ArrayList, override iterator(), take that iterator and wrap & delegate it to my own Iterator object that denies access to remove. (Or wrap and delegate ArrayList itself and do the same thing)
Collections.unmodifiableList does the same thing, basically.
But this would cause two objects to be created each and every time MyArrayList.iterator() is called, which in my environment is suboptimal.
Ideas?
edit:
In this environment, GCing small objects is a major major problem. This environment calls list iterators hundreds of millions of times in very short periods. We need as little GC thrashing as possible. This is not premature optimization. This is very late optimization. This is not some toy app. This is a clustered web-scale system that is running at the absolute limit of the hardware.
Collections.unmodifiablelist, as you mention, is probably the best way to go. I doubt that you have indeed profiled your program as a whole and found out that the creation of iterators is indeed a bottle neck in the execution.Actually, Java creates tons and tons of temporary objects. This is not good per see, but due to this it is very optimized to do it efficiently.
Btw, the fact that you’re trying to access private members of the ArrayList actually smells a little. Why not create an iterator based on
size()andget(int index)if you really don’t want to create two objects when iterating over the list?