1 ///////////////////////////////////////////////////////////////////////////////////////////////
2 // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3 // Copyright (C) 2001-2026 the original author or authors.
4 //
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Lesser General Public
7 // License as published by the Free Software Foundation; either
8 // version 2.1 of the License, or (at your option) any later version.
9 //
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // Lesser General Public License for more details.
14 //
15 // You should have received a copy of the GNU Lesser General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 ///////////////////////////////////////////////////////////////////////////////////////////////
19
20 package com.puppycrawl.tools.checkstyle.checks.coding;
21
22 import java.util.HashMap;
23 import java.util.Map;
24
25 import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
26 import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
27 import com.puppycrawl.tools.checkstyle.api.DetailAST;
28 import com.puppycrawl.tools.checkstyle.api.FullIdent;
29 import com.puppycrawl.tools.checkstyle.api.TokenTypes;
30 import com.puppycrawl.tools.checkstyle.utils.CheckUtil;
31
32 /**
33 * <div>
34 * Checks that classes that either override {@code equals()} or {@code hashCode()} also
35 * overrides the other.
36 * This check only verifies that the method declarations match {@code Object.equals(Object)} and
37 * {@code Object.hashCode()} exactly to be considered an override. This check does not verify
38 * invalid method names, parameters other than {@code Object}, or anything else.
39 * </div>
40 *
41 * <p>
42 * Rationale: The contract of {@code equals()} and {@code hashCode()} requires that
43 * equal objects have the same hashCode. Therefore, whenever you override
44 * {@code equals()} you must override {@code hashCode()} to ensure that your class can
45 * be used in hash-based collections.
46 * </p>
47 *
48 * @since 3.0
49 */
50 @FileStatefulCheck
51 public class EqualsHashCodeCheck
52 extends AbstractCheck {
53
54 // implementation note: we have to use the following members to
55 // keep track of definitions in different inner classes
56
57 /**
58 * A key is pointing to the warning message text in "messages.properties"
59 * file.
60 */
61 public static final String MSG_KEY_HASHCODE = "equals.noHashCode";
62
63 /**
64 * A key is pointing to the warning message text in "messages.properties"
65 * file.
66 */
67 public static final String MSG_KEY_EQUALS = "equals.noEquals";
68
69 /** Maps OBJ_BLOCK to the method definition of equals(). */
70 private final Map<DetailAST, DetailAST> objBlockWithEquals = new HashMap<>();
71
72 /** Maps OBJ_BLOCKs to the method definition of hashCode(). */
73 private final Map<DetailAST, DetailAST> objBlockWithHashCode = new HashMap<>();
74
75 /**
76 * Creates a new {@code EqualsHashCodeCheck} instance.
77 */
78 public EqualsHashCodeCheck() {
79 // no code by default
80 }
81
82 @Override
83 public int[] getDefaultTokens() {
84 return getRequiredTokens();
85 }
86
87 @Override
88 public int[] getAcceptableTokens() {
89 return getRequiredTokens();
90 }
91
92 @Override
93 public int[] getRequiredTokens() {
94 return new int[] {TokenTypes.METHOD_DEF};
95 }
96
97 @Override
98 public void beginTree(DetailAST rootAST) {
99 objBlockWithEquals.clear();
100 objBlockWithHashCode.clear();
101 }
102
103 @Override
104 public void visitToken(DetailAST ast) {
105 if (isEqualsMethod(ast)) {
106 objBlockWithEquals.put(ast.getParent(), ast);
107 }
108 else if (isHashCodeMethod(ast)) {
109 objBlockWithHashCode.put(ast.getParent(), ast);
110 }
111 }
112
113 /**
114 * Determines if an AST is a valid Equals method implementation.
115 *
116 * @param ast the AST to check
117 * @return true if the {code ast} is an Equals method.
118 */
119 private static boolean isEqualsMethod(DetailAST ast) {
120 final DetailAST modifiers = ast.getFirstChild();
121 final DetailAST parameters = ast.findFirstToken(TokenTypes.PARAMETERS);
122
123 return CheckUtil.isEqualsMethod(ast)
124 && isObjectParam(parameters.getFirstChild())
125 && (ast.findFirstToken(TokenTypes.SLIST) != null
126 || modifiers.findFirstToken(TokenTypes.LITERAL_NATIVE) != null);
127 }
128
129 /**
130 * Determines if an AST is a valid HashCode method implementation.
131 *
132 * @param ast the AST to check
133 * @return true if the {code ast} is a HashCode method.
134 */
135 private static boolean isHashCodeMethod(DetailAST ast) {
136 final DetailAST modifiers = ast.getFirstChild();
137 final DetailAST methodName = ast.findFirstToken(TokenTypes.IDENT);
138 final DetailAST parameters = ast.findFirstToken(TokenTypes.PARAMETERS);
139
140 return "hashCode".equals(methodName.getText())
141 && parameters.getFirstChild() == null
142 && (ast.findFirstToken(TokenTypes.SLIST) != null
143 || modifiers.findFirstToken(TokenTypes.LITERAL_NATIVE) != null);
144 }
145
146 /**
147 * Determines if an AST is a formal param of type Object.
148 *
149 * @param paramNode the AST to check
150 * @return true if firstChild is a parameter of an Object type.
151 */
152 private static boolean isObjectParam(DetailAST paramNode) {
153 final DetailAST typeNode = paramNode.findFirstToken(TokenTypes.TYPE);
154 final FullIdent fullIdent = FullIdent.createFullIdentBelow(typeNode);
155 final String name = fullIdent.getText();
156 return "Object".equals(name) || "java.lang.Object".equals(name);
157 }
158
159 @Override
160 public void finishTree(DetailAST rootAST) {
161 objBlockWithEquals
162 .entrySet().stream().filter(detailASTDetailASTEntry -> {
163 return objBlockWithHashCode.remove(detailASTDetailASTEntry.getKey()) == null;
164 }).forEach(detailASTDetailASTEntry -> {
165 final DetailAST equalsAST = detailASTDetailASTEntry.getValue();
166 log(equalsAST, MSG_KEY_HASHCODE);
167 });
168 objBlockWithHashCode.forEach((key, equalsAST) -> log(equalsAST, MSG_KEY_EQUALS));
169 }
170
171 }