018-004-002

Hash Code: Implementing hashCode Method

Easy

Problem Description

Hash Code: Implementing hashCode method

In this problem, you will create a program that overrides the hashCode() method in a Recipe class to calculate a hash code value from the recipe name and cooking time, and displays the result to standard output.

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

Normal case
Input:
Curry
30
Expected Output:
=== Hash Code Calculation ===
Recipe: Curry
Cooking Time: 30 minutes
━━━━━━━━━━━━━━━━
Hash Code: 2029715544
Normal case
Input:
Pasta
20
Expected Output:
=== Hash Code Calculation ===
Recipe: Pasta
Cooking Time: 20 minutes
━━━━━━━━━━━━━━━━
Hash Code: -1911512250

Your Solution

Current Mode:● My Code
Recipe.java🔒
Solution.java🔒
2/6 ファイル147B
⚠️警告
  • No main method found
import java.util.Objects;
import java.util.Scanner;

class Recipe {
}
0 B / 5 MB

You have 10 free executions remaining