Skip to content

Commit 9bada62

Browse files
committed
add an example of record equals/hashCode/toString
1 parent 003a072 commit 9bada62

3 files changed

+32
-2
lines changed

chapter12-equals_hashCode_toString.jsh

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,4 +125,14 @@ System.out.println(user1);
125125

126126
// For a record, the methods `equals()`/`hashCode()` and `toString()` are already provided
127127
// so usually you don't have to provide a new implementation.
128-
128+
record User(String name, int age) {
129+
public User {
130+
Objects.requireNonNull(name);
131+
}
132+
// the compiler automatically adds equals/hashCode/toString !
133+
}
134+
var user1 = new User("Bob", 31);
135+
var user2 = new User("Bob", 31);
136+
System.out.println(user1.equals(user2));
137+
System.out.println(user1.hashCode() == user2.hashCode());
138+
System.out.println(user1);

guide/chapter12-equals_hashCode_toString.md

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,4 +127,16 @@ System.out.println(user1);
127127

128128
For a record, the methods `equals()`/`hashCode()` and `toString()` are already provided
129129
so usually you don't have to provide a new implementation.
130-
130+
```java
131+
record User(String name, int age) {
132+
public User {
133+
Objects.requireNonNull(name);
134+
}
135+
// the compiler automatically adds equals/hashCode/toString !
136+
}
137+
var user1 = new User("Bob", 31);
138+
var user2 = new User("Bob", 31);
139+
System.out.println(user1.equals(user2));
140+
System.out.println(user1.hashCode() == user2.hashCode());
141+
System.out.println(user1);
142+
```

jupyter/chapter12-equals_hashCode_toString.ipynb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,14 @@
8282
"metadata": {},
8383
"source": ["For a record, the methods `equals()`/`hashCode()` and `toString()` are already provided\n", "so usually you don't have to provide a new implementation.\n"]
8484
}
85+
,
86+
{
87+
"cell_type": "code",
88+
"execution_count": null,
89+
"metadata": {},
90+
"outputs": [],
91+
"source": ["record User(String name, int age) {\n", " public User {\n", " Objects.requireNonNull(name);\n", " }\n", " // the compiler automatically adds equals/hashCode/toString !\n", "}\n", "var user1 = new User(\"Bob\", 31);\n", "var user2 = new User(\"Bob\", 31);\n", "System.out.println(user1.equals(user2));\n", "System.out.println(user1.hashCode() == user2.hashCode());\n", "System.out.println(user1);\n"]
92+
}
8593
],
8694
"metadata": {
8795
"kernelspec": {

0 commit comments

Comments
 (0)