[antlr-interest] Label.hashCode not consistant with equals

Ulf Ochsenfahrt ulf at ofahrt.de
Thu Aug 16 08:21:36 PDT 2007


Hi,

I was looking though the antlr source searching for a place to fix the 
issue with the overlong specialStateTransition method, when I realized 
that the Label.hashCode is _not_ consistant with its equals method. In 
particular, the java.lang.Object JavaDocs state:

If two objects are equal according to the equals(Object) method, then 
calling the hashCode method on each of the two objects must produce the 
same integer result.

The following test case should thus pass:
package org.antlr.test;

import junit.framework.TestCase;

import org.antlr.analysis.Label;
import org.antlr.analysis.SemanticContext.Predicate;
import org.antlr.analysis.SemanticContext.TruePredicate;
import org.antlr.tool.GrammarAST;

public class TestLabel extends TestCase
{
	
	public void testLabelEquals() throws Exception {
		Label l0 = new Label(new Predicate(new GrammarAST(3, "abc")));
		Label l1 = new Label(new TruePredicate());
		if (l0.equals(l1))
			assertEquals(l0.hashCode(), l1.hashCode());
	}
	
}

If the labels are equal, they should have identical hash codes. This is 
- unfortunately - not the case, because the equals method in Label does 
not check the SemanticContext if it is a semantic predicate. I believe 
the following three lines would fix that:

if ( label==SEMPRED ) {
	return this.predicate.equals(((Label)o).predicate);
}

Also, equals implementations often test on object equality first, 
because this is very fast, i.e.: if ( this == o ) return true;

Cheers,

-- Ulf
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/x-pkcs7-signature
Size: 3613 bytes
Desc: S/MIME Cryptographic Signature
Url : http://www.antlr.org/pipermail/antlr-interest/attachments/20070816/d0bb17e4/attachment.bin 


More information about the antlr-interest mailing list