018-004-002
Hash Code: Implementing hashCode Method
Easy
Problem Description
Hash Code: Implementing hashCode Method
Learning Objective: Learn to understand hash code and implement hashCode method
Create recipe class and implement hashCode() method to calculate hash code value from recipe name and cooking time. Hash code is integer value for fast object search and comparison. Used for efficient object management in collections like HashSet and HashMap.
Example 1: Same Content Recipes Have Same Hash Code
Recipe recipe1 = new Recipe("Curry", 30);
Recipe recipe2 = new Recipe("Curry", 30);
System.out.println(recipe1.hashCode()); // 2074474418
System.out.println(recipe2.hashCode()); // 2074474418 (same value)
System.out.println(recipe1.equals(recipe2)); // true
```java
With same recipe name and cooking time, separately created objects return same hash code value. This enables correct duplicate detection in HashSet.
### Example 2: Different Content Recipes Have Different Hash Codes
```java
Recipe curry = new Recipe("Curry", 30);
Recipe pasta = new Recipe("Pasta", 20);
System.out.println(curry.hashCode()); // 2074474418
System.out.println(pasta.hashCode()); // 78916396 (different value)
System.out.println(curry.equals(pasta)); // false
```java
If recipe name or cooking time differs, usually different hash code values are generated. This enables efficient hash table search.
### Example 3: Duplicate Elimination in HashSet
```java
Set<Recipe> recipes = new HashSet<>();
recipes.add(new Recipe("Curry", 30));
recipes.add(new Recipe("Curry", 30)); // Same content, not added
recipes.add(new Recipe("Pasta", 20));
System.out.println(recipes.size()); // 2 (duplicates eliminated)
```java
HashSet determines duplicates using hashCode() and equals(). If same hash code and equals() is true, determined as duplicate.
## Input
Line 1: Recipe name
Line 2: Cooking time (minutes)
## Output
```java
=== Hash Code Calculation ===
Recipe: [recipe name]
Cooking Time: [time] minutes
━━━━━━━━━━━━━━━━
Hash Code: [hash code value]
Test Cases
※ Output examples follow programming industry standards
Input:
Curry 30
Expected Output:
=== Hash Code Calculation === Recipe: Curry Cooking Time: 30 minutes ━━━━━━━━━━━━━━━━ Hash Code: 2029715544
Input:
Pasta 20
Expected Output:
=== Hash Code Calculation === Recipe: Pasta Cooking Time: 20 minutes ━━━━━━━━━━━━━━━━ Hash Code: -1911512250
Input:
Curry 30
Expected Output:
=== Hash Code Calculation === Recipe: Curry Cooking Time: 30 minutes ━━━━━━━━━━━━━━━━ Hash Code: 2029715544
❌ Some tests failed
Your Solution
Current Mode:● My Code
99
1
2
3
4
5
6
7
8
9
10
›
⌄
⌄
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Write your code here
sc.close();
}
}
0 B / 5 MB
You have 9 free executions remaining
