Search code examples
javacollectionsarraylistoverridingextend

I want to extend ArrayList to implement but cannnot access to elementData private var


I would like to know how can I override indexOf() method in a subclass of ArrayList. I need to use the same accessing that super to the private transient elementData var.

How can I solve my design?

EDIT: Could it be a valid solution changing the call to elementData[i] to a similar this.get(i) (which is actually allowed?). Would it corrupt or break the logic someway?


Solution

  • You shouldn't, basically. Use composition instead, if you want to create a collection which behaves in a way which isn't the same as ArrayList. The private details of ArrayList are private for good reason; they're implementation details which could change between versions, and your code shouldn't care about them.

    (It's possible that extending ArrayList is actually a valid approach, but unlikely IMO. You haven't said what you're really trying to achieve, just what's stopping you from achieving it. If you could tell us more about the big picture, we're more likely to be able to help.)