0

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?

Whimusical
  • 6,401
  • 11
  • 62
  • 105

2 Answers2

5

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.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I am doing a wrapper for my Arraylist so I can use a different equal-compare logic as explained here: http://stackoverflow.com/questions/11758220/a-mechanism-for-having-different-equals-physical-equals-and-logical-equals-on. But I dont want to implement the 700 hundred methods of interface List. – Whimusical Aug 01 '12 at 17:08
  • 2
    @user1352530 there are far fewer than 700 methods in `List`. Most IDEs will create the stub methods for you. – Steve Kuo Aug 01 '12 at 17:13
  • 1
    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? – Whimusical Aug 01 '12 at 17:15
  • 2
    Absolutely, yes. Or, even better -- don't violate the `List` contract by using a different `equals()` logic; instead write a method that takes a `List` and an `Object` and finds the index of that object according to your different logic. – Louis Wasserman Aug 01 '12 at 17:26
1

You could create a container, which provides the same methods as an ArrayList and has a field of type ArrayList (for the data storage). Then you add all ArrayList methods to your container class, which execute the corresponding method on the ArrayList (field) except those you want to override.

Peter Ilfrich
  • 3,727
  • 3
  • 31
  • 35