001/////////////////////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code and other text files for adherence to a set of rules. 003// Copyright (C) 2001-2026 the original author or authors. 004// 005// This library is free software; you can redistribute it and/or 006// modify it under the terms of the GNU Lesser General Public 007// License as published by the Free Software Foundation; either 008// version 2.1 of the License, or (at your option) any later version. 009// 010// This library is distributed in the hope that it will be useful, 011// but WITHOUT ANY WARRANTY; without even the implied warranty of 012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 013// Lesser General Public License for more details. 014// 015// You should have received a copy of the GNU Lesser General Public 016// License along with this library; if not, write to the Free Software 017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 018/////////////////////////////////////////////////////////////////////////////////////////////// 019 020package com.puppycrawl.tools.checkstyle.checks.coding; 021 022import java.util.HashMap; 023import java.util.Map; 024 025import com.puppycrawl.tools.checkstyle.FileStatefulCheck; 026import com.puppycrawl.tools.checkstyle.api.AbstractCheck; 027import com.puppycrawl.tools.checkstyle.api.DetailAST; 028import com.puppycrawl.tools.checkstyle.api.FullIdent; 029import com.puppycrawl.tools.checkstyle.api.TokenTypes; 030import com.puppycrawl.tools.checkstyle.utils.CheckUtil; 031 032/** 033 * <div> 034 * Checks that classes that either override {@code equals()} or {@code hashCode()} also 035 * overrides the other. 036 * This check only verifies that the method declarations match {@code Object.equals(Object)} and 037 * {@code Object.hashCode()} exactly to be considered an override. This check does not verify 038 * invalid method names, parameters other than {@code Object}, or anything else. 039 * </div> 040 * 041 * <p> 042 * Rationale: The contract of {@code equals()} and {@code hashCode()} requires that 043 * equal objects have the same hashCode. Therefore, whenever you override 044 * {@code equals()} you must override {@code hashCode()} to ensure that your class can 045 * be used in hash-based collections. 046 * </p> 047 * 048 * @since 3.0 049 */ 050@FileStatefulCheck 051public class EqualsHashCodeCheck extends AbstractCheck { 052 053 // implementation note: we have to use the following members to 054 // keep track of definitions in different inner classes 055 056 /** 057 * A key is pointing to the warning message text in "messages.properties" file. 058 */ 059 public static final String MSG_KEY_HASHCODE = "equals.noHashCode"; 060 061 /** 062 * A key is pointing to the warning message text in "messages.properties" file. 063 */ 064 public static final String MSG_KEY_EQUALS = "equals.noEquals"; 065 066 /** Maps OBJ_BLOCK to the method definition of equals(). */ 067 private final Map<DetailAST, DetailAST> objBlockWithEquals = new HashMap<>(); 068 069 /** Maps OBJ_BLOCKs to the method definition of hashCode(). */ 070 private final Map<DetailAST, DetailAST> objBlockWithHashCode = new HashMap<>(); 071 072 /** 073 * Creates a new {@code EqualsHashCodeCheck} instance. 074 */ 075 public EqualsHashCodeCheck() { 076 // no code by default 077 } 078 079 @Override 080 public int[] getDefaultTokens() { 081 return getRequiredTokens(); 082 } 083 084 @Override 085 public int[] getAcceptableTokens() { 086 return getRequiredTokens(); 087 } 088 089 @Override 090 public int[] getRequiredTokens() { 091 return new int[] {TokenTypes.METHOD_DEF}; 092 } 093 094 @Override 095 public void beginTree(DetailAST rootAST) { 096 objBlockWithEquals.clear(); 097 objBlockWithHashCode.clear(); 098 } 099 100 @Override 101 public void visitToken(DetailAST ast) { 102 if (isEqualsMethod(ast)) { 103 objBlockWithEquals.put(ast.getParent(), ast); 104 } 105 else if (isHashCodeMethod(ast)) { 106 objBlockWithHashCode.put(ast.getParent(), ast); 107 } 108 } 109 110 /** 111 * Determines if an AST is a valid Equals method implementation. 112 * 113 * @param ast the AST to check 114 * @return true if the {code ast} is an Equals method. 115 */ 116 private static boolean isEqualsMethod(DetailAST ast) { 117 final DetailAST modifiers = ast.getFirstChild(); 118 final DetailAST parameters = ast.findFirstToken(TokenTypes.PARAMETERS); 119 120 return CheckUtil.isEqualsMethod(ast) 121 && isObjectParam(parameters.getFirstChild()) 122 && (ast.findFirstToken(TokenTypes.SLIST) != null 123 || modifiers.findFirstToken(TokenTypes.LITERAL_NATIVE) != null); 124 } 125 126 /** 127 * Determines if an AST is a valid HashCode method implementation. 128 * 129 * @param ast the AST to check 130 * @return true if the {code ast} is a HashCode method. 131 */ 132 private static boolean isHashCodeMethod(DetailAST ast) { 133 final DetailAST modifiers = ast.getFirstChild(); 134 final DetailAST methodName = ast.findFirstToken(TokenTypes.IDENT); 135 final DetailAST parameters = ast.findFirstToken(TokenTypes.PARAMETERS); 136 137 return "hashCode".equals(methodName.getText()) 138 && parameters.getFirstChild() == null 139 && (ast.findFirstToken(TokenTypes.SLIST) != null 140 || modifiers.findFirstToken(TokenTypes.LITERAL_NATIVE) != null); 141 } 142 143 /** 144 * Determines if an AST is a formal param of type Object. 145 * 146 * @param paramNode the AST to check 147 * @return true if firstChild is a parameter of an Object type. 148 */ 149 private static boolean isObjectParam(DetailAST paramNode) { 150 final DetailAST typeNode = paramNode.findFirstToken(TokenTypes.TYPE); 151 final FullIdent fullIdent = FullIdent.createFullIdentBelow(typeNode); 152 final String name = fullIdent.getText(); 153 return "Object".equals(name) || "java.lang.Object".equals(name); 154 } 155 156 @Override 157 public void finishTree(DetailAST rootAST) { 158 objBlockWithEquals 159 .entrySet().stream().filter(detailASTDetailASTEntry -> { 160 return objBlockWithHashCode.remove(detailASTDetailASTEntry.getKey()) == null; 161 }).forEach(detailASTDetailASTEntry -> { 162 final DetailAST equalsAST = detailASTDetailASTEntry.getValue(); 163 log(equalsAST, MSG_KEY_HASHCODE); 164 }); 165 objBlockWithHashCode.forEach((key, equalsAST) -> log(equalsAST, MSG_KEY_EQUALS)); 166 } 167 168}