Override ArrayList indexOf

Ok, so I have a TreeNode class that wraps a Character inside a node of a tree. In order to make things easier, I overrode the equals and compareTo methods so it accepted not only TreeNodes, but also Characters, as the TreeNode is just a wrapper to a Character.

I'm working with an ArrayList<TreeNode>, and I would like to have the indexOf method when receiving a Character to return me the index of the TreeNode that wraps that Character, if it exists.

Reading the indexOf definition, it uses the equals method to make the comparison, so i figured that, as my TreeNode.equals(Object o) method is already able to receive Characters, the indexOf method would work for MyArrayList.indexOf(someCharacter), but it doesn't.

I put a breakpoint in the TreeNode.equals(Object o) method to find out if it was called after a call to MyArrayList.indexOf(someCharacter), but it never gets called.

Is there a way to implement this behaviour, or should I extend the ArrayList class to implement the behaviour I want?

[1040 byte] By [Master_Grasshoppera] at [2007-11-27 4:26:19]
# 1

You've broken one of the fundamental parts of the equals() contract. Specifically, the equals() method should be symmetrical. That is x.equals(y) should give the same result as y.equals(x).

In this case: someTreeNode.equals(someCharacter) does not give the same result as someCharacter.equals(someTreeNode) - because Character knows nothing about your TreeNode class.

If you look in the code for ArrayList, you will see that it does thingYouAreLookingFor.equals(each of the items in the list). In other words, someCharacter.equals(someTreeNode). Hence the outcome you are experiencing.

Solution: firstly, fix your equals() so that it behaves according to the contract it is implementing, and secondly, you have no choice but to pass a TreeNode into the indexOf() method - so you'll have to create a temporary one for the purposes of the comparison.

(PS for the same reason, don't ever use instanceof in an equals method)

dannyyatesa at 2007-7-12 9:34:47 > top of Java-index,Core,Core APIs...
# 2
Got it. This is another one of the "Things you can but must not do".
Master_Grasshoppera at 2007-7-12 9:34:47 > top of Java-index,Core,Core APIs...