How to compare objects contained in the set? What would be a good hashcode and equals implementation here?
import java.util.*;
public class Tester
{
public static void main(String args)
{
Set<Point> set = new HashSet<Point>();
Point A = new Point(0, 0);
set.add(A);
Point B = new Point(0, 0);
System.out.println(set.contains(B));
}
}
class Point
{
int x, y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public boolean equals(Object o)
{
// Not sure/
}
public int hashcode()
{
// Not sure?
}
}
I'm using a Point object to represent every cell of a 2d matrix. For DFS, I need to mark nodes as visited. However, the code returns false although it has object with value (0, 0). I think this probably requires a hashcode and equals implementation since by default the equals() looks for object reference.
So my question is, what would be a good hashcode and equals implementation here?
1. No constraints on the x and y.
2. x and y at most would be 1000.
java
add a comment |
import java.util.*;
public class Tester
{
public static void main(String args)
{
Set<Point> set = new HashSet<Point>();
Point A = new Point(0, 0);
set.add(A);
Point B = new Point(0, 0);
System.out.println(set.contains(B));
}
}
class Point
{
int x, y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public boolean equals(Object o)
{
// Not sure/
}
public int hashcode()
{
// Not sure?
}
}
I'm using a Point object to represent every cell of a 2d matrix. For DFS, I need to mark nodes as visited. However, the code returns false although it has object with value (0, 0). I think this probably requires a hashcode and equals implementation since by default the equals() looks for object reference.
So my question is, what would be a good hashcode and equals implementation here?
1. No constraints on the x and y.
2. x and y at most would be 1000.
java
1
Why not just use the auto-generated methods given by the IDE?
– Nicholas K
Jan 1 at 7:14
@NicholasK this is more like a leetcode exercise
– user2609410
Jan 1 at 7:23
add a comment |
import java.util.*;
public class Tester
{
public static void main(String args)
{
Set<Point> set = new HashSet<Point>();
Point A = new Point(0, 0);
set.add(A);
Point B = new Point(0, 0);
System.out.println(set.contains(B));
}
}
class Point
{
int x, y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public boolean equals(Object o)
{
// Not sure/
}
public int hashcode()
{
// Not sure?
}
}
I'm using a Point object to represent every cell of a 2d matrix. For DFS, I need to mark nodes as visited. However, the code returns false although it has object with value (0, 0). I think this probably requires a hashcode and equals implementation since by default the equals() looks for object reference.
So my question is, what would be a good hashcode and equals implementation here?
1. No constraints on the x and y.
2. x and y at most would be 1000.
java
import java.util.*;
public class Tester
{
public static void main(String args)
{
Set<Point> set = new HashSet<Point>();
Point A = new Point(0, 0);
set.add(A);
Point B = new Point(0, 0);
System.out.println(set.contains(B));
}
}
class Point
{
int x, y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public boolean equals(Object o)
{
// Not sure/
}
public int hashcode()
{
// Not sure?
}
}
I'm using a Point object to represent every cell of a 2d matrix. For DFS, I need to mark nodes as visited. However, the code returns false although it has object with value (0, 0). I think this probably requires a hashcode and equals implementation since by default the equals() looks for object reference.
So my question is, what would be a good hashcode and equals implementation here?
1. No constraints on the x and y.
2. x and y at most would be 1000.
java
java
edited Jan 1 at 7:21
John Kugelman
243k54406457
243k54406457
asked Jan 1 at 7:05
user2609410user2609410
6910
6910
1
Why not just use the auto-generated methods given by the IDE?
– Nicholas K
Jan 1 at 7:14
@NicholasK this is more like a leetcode exercise
– user2609410
Jan 1 at 7:23
add a comment |
1
Why not just use the auto-generated methods given by the IDE?
– Nicholas K
Jan 1 at 7:14
@NicholasK this is more like a leetcode exercise
– user2609410
Jan 1 at 7:23
1
1
Why not just use the auto-generated methods given by the IDE?
– Nicholas K
Jan 1 at 7:14
Why not just use the auto-generated methods given by the IDE?
– Nicholas K
Jan 1 at 7:14
@NicholasK this is more like a leetcode exercise
– user2609410
Jan 1 at 7:23
@NicholasK this is more like a leetcode exercise
– user2609410
Jan 1 at 7:23
add a comment |
2 Answers
2
active
oldest
votes
Your equals
method should return true
if and only if both objects are intances of Point
and both have the same x
and y
values:
@Override
public boolean equals(Object o)
{
if (o == this)
return true;
if (!(o instanceof Point))
return false;
Point other = (Point) o;
return this.x == other.x && this.y == other.y;
}
For hashCode
, you can use a helper method:
@Override
public int hashCode()
{
return Objects.hash(x,y);
}
EDIT: using the @Override
annotation is optional, but it will save you from typos such as hashcode
instead of hashCode
.
Can you explain what purpose does this solve?return Objects.hash(x,y);
And how it works internally?
– user2609410
Jan 1 at 7:13
And I tried it out, still shows false. @Eran (updated the code in my description) still fails
– user2609410
Jan 1 at 7:17
1
@user2609410 it returns a function ofx
andy
, so ifpoint1.equals(point2)==true
,point1.hashCode()==point2.hashCode()
will also be true. The actual implementation is31 * (31 + x) + y
– Eran
Jan 1 at 7:18
@user2609410 that's because you had a typo - it should behashCode
, nothashcode
– Eran
Jan 1 at 7:21
Thanks! Ill update the desc and mark your answer as solution
– user2609410
Jan 1 at 7:21
add a comment |
You used HashSet
for Set
implementation which uses hashing to store elements. hashcode()
and equals()
are used for hashing and comparing elements. There are some guidelines to override hashcode()
and equals()
method.
The general contract of hashCode is:
- hashcode method should consistent. That is it should return same integer on mulitple call on same object.
- If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
- It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
Guideline for equals method.
- It is reflexive: for any non-null reference value x, x.equals(x) should return true.
- It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
- It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
- It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
- For any non-null reference value x, x.equals(null) should return false.
Source:-Hashcode Javadoc, Equals javadoc
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53993657%2fhow-to-compare-objects-contained-in-the-set-what-would-be-a-good-hashcode-and-e%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
Your equals
method should return true
if and only if both objects are intances of Point
and both have the same x
and y
values:
@Override
public boolean equals(Object o)
{
if (o == this)
return true;
if (!(o instanceof Point))
return false;
Point other = (Point) o;
return this.x == other.x && this.y == other.y;
}
For hashCode
, you can use a helper method:
@Override
public int hashCode()
{
return Objects.hash(x,y);
}
EDIT: using the @Override
annotation is optional, but it will save you from typos such as hashcode
instead of hashCode
.
Can you explain what purpose does this solve?return Objects.hash(x,y);
And how it works internally?
– user2609410
Jan 1 at 7:13
And I tried it out, still shows false. @Eran (updated the code in my description) still fails
– user2609410
Jan 1 at 7:17
1
@user2609410 it returns a function ofx
andy
, so ifpoint1.equals(point2)==true
,point1.hashCode()==point2.hashCode()
will also be true. The actual implementation is31 * (31 + x) + y
– Eran
Jan 1 at 7:18
@user2609410 that's because you had a typo - it should behashCode
, nothashcode
– Eran
Jan 1 at 7:21
Thanks! Ill update the desc and mark your answer as solution
– user2609410
Jan 1 at 7:21
add a comment |
Your equals
method should return true
if and only if both objects are intances of Point
and both have the same x
and y
values:
@Override
public boolean equals(Object o)
{
if (o == this)
return true;
if (!(o instanceof Point))
return false;
Point other = (Point) o;
return this.x == other.x && this.y == other.y;
}
For hashCode
, you can use a helper method:
@Override
public int hashCode()
{
return Objects.hash(x,y);
}
EDIT: using the @Override
annotation is optional, but it will save you from typos such as hashcode
instead of hashCode
.
Can you explain what purpose does this solve?return Objects.hash(x,y);
And how it works internally?
– user2609410
Jan 1 at 7:13
And I tried it out, still shows false. @Eran (updated the code in my description) still fails
– user2609410
Jan 1 at 7:17
1
@user2609410 it returns a function ofx
andy
, so ifpoint1.equals(point2)==true
,point1.hashCode()==point2.hashCode()
will also be true. The actual implementation is31 * (31 + x) + y
– Eran
Jan 1 at 7:18
@user2609410 that's because you had a typo - it should behashCode
, nothashcode
– Eran
Jan 1 at 7:21
Thanks! Ill update the desc and mark your answer as solution
– user2609410
Jan 1 at 7:21
add a comment |
Your equals
method should return true
if and only if both objects are intances of Point
and both have the same x
and y
values:
@Override
public boolean equals(Object o)
{
if (o == this)
return true;
if (!(o instanceof Point))
return false;
Point other = (Point) o;
return this.x == other.x && this.y == other.y;
}
For hashCode
, you can use a helper method:
@Override
public int hashCode()
{
return Objects.hash(x,y);
}
EDIT: using the @Override
annotation is optional, but it will save you from typos such as hashcode
instead of hashCode
.
Your equals
method should return true
if and only if both objects are intances of Point
and both have the same x
and y
values:
@Override
public boolean equals(Object o)
{
if (o == this)
return true;
if (!(o instanceof Point))
return false;
Point other = (Point) o;
return this.x == other.x && this.y == other.y;
}
For hashCode
, you can use a helper method:
@Override
public int hashCode()
{
return Objects.hash(x,y);
}
EDIT: using the @Override
annotation is optional, but it will save you from typos such as hashcode
instead of hashCode
.
edited Jan 1 at 7:23
answered Jan 1 at 7:10
EranEran
286k37464553
286k37464553
Can you explain what purpose does this solve?return Objects.hash(x,y);
And how it works internally?
– user2609410
Jan 1 at 7:13
And I tried it out, still shows false. @Eran (updated the code in my description) still fails
– user2609410
Jan 1 at 7:17
1
@user2609410 it returns a function ofx
andy
, so ifpoint1.equals(point2)==true
,point1.hashCode()==point2.hashCode()
will also be true. The actual implementation is31 * (31 + x) + y
– Eran
Jan 1 at 7:18
@user2609410 that's because you had a typo - it should behashCode
, nothashcode
– Eran
Jan 1 at 7:21
Thanks! Ill update the desc and mark your answer as solution
– user2609410
Jan 1 at 7:21
add a comment |
Can you explain what purpose does this solve?return Objects.hash(x,y);
And how it works internally?
– user2609410
Jan 1 at 7:13
And I tried it out, still shows false. @Eran (updated the code in my description) still fails
– user2609410
Jan 1 at 7:17
1
@user2609410 it returns a function ofx
andy
, so ifpoint1.equals(point2)==true
,point1.hashCode()==point2.hashCode()
will also be true. The actual implementation is31 * (31 + x) + y
– Eran
Jan 1 at 7:18
@user2609410 that's because you had a typo - it should behashCode
, nothashcode
– Eran
Jan 1 at 7:21
Thanks! Ill update the desc and mark your answer as solution
– user2609410
Jan 1 at 7:21
Can you explain what purpose does this solve?
return Objects.hash(x,y);
And how it works internally?– user2609410
Jan 1 at 7:13
Can you explain what purpose does this solve?
return Objects.hash(x,y);
And how it works internally?– user2609410
Jan 1 at 7:13
And I tried it out, still shows false. @Eran (updated the code in my description) still fails
– user2609410
Jan 1 at 7:17
And I tried it out, still shows false. @Eran (updated the code in my description) still fails
– user2609410
Jan 1 at 7:17
1
1
@user2609410 it returns a function of
x
and y
, so if point1.equals(point2)==true
, point1.hashCode()==point2.hashCode()
will also be true. The actual implementation is 31 * (31 + x) + y
– Eran
Jan 1 at 7:18
@user2609410 it returns a function of
x
and y
, so if point1.equals(point2)==true
, point1.hashCode()==point2.hashCode()
will also be true. The actual implementation is 31 * (31 + x) + y
– Eran
Jan 1 at 7:18
@user2609410 that's because you had a typo - it should be
hashCode
, not hashcode
– Eran
Jan 1 at 7:21
@user2609410 that's because you had a typo - it should be
hashCode
, not hashcode
– Eran
Jan 1 at 7:21
Thanks! Ill update the desc and mark your answer as solution
– user2609410
Jan 1 at 7:21
Thanks! Ill update the desc and mark your answer as solution
– user2609410
Jan 1 at 7:21
add a comment |
You used HashSet
for Set
implementation which uses hashing to store elements. hashcode()
and equals()
are used for hashing and comparing elements. There are some guidelines to override hashcode()
and equals()
method.
The general contract of hashCode is:
- hashcode method should consistent. That is it should return same integer on mulitple call on same object.
- If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
- It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
Guideline for equals method.
- It is reflexive: for any non-null reference value x, x.equals(x) should return true.
- It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
- It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
- It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
- For any non-null reference value x, x.equals(null) should return false.
Source:-Hashcode Javadoc, Equals javadoc
add a comment |
You used HashSet
for Set
implementation which uses hashing to store elements. hashcode()
and equals()
are used for hashing and comparing elements. There are some guidelines to override hashcode()
and equals()
method.
The general contract of hashCode is:
- hashcode method should consistent. That is it should return same integer on mulitple call on same object.
- If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
- It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
Guideline for equals method.
- It is reflexive: for any non-null reference value x, x.equals(x) should return true.
- It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
- It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
- It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
- For any non-null reference value x, x.equals(null) should return false.
Source:-Hashcode Javadoc, Equals javadoc
add a comment |
You used HashSet
for Set
implementation which uses hashing to store elements. hashcode()
and equals()
are used for hashing and comparing elements. There are some guidelines to override hashcode()
and equals()
method.
The general contract of hashCode is:
- hashcode method should consistent. That is it should return same integer on mulitple call on same object.
- If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
- It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
Guideline for equals method.
- It is reflexive: for any non-null reference value x, x.equals(x) should return true.
- It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
- It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
- It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
- For any non-null reference value x, x.equals(null) should return false.
Source:-Hashcode Javadoc, Equals javadoc
You used HashSet
for Set
implementation which uses hashing to store elements. hashcode()
and equals()
are used for hashing and comparing elements. There are some guidelines to override hashcode()
and equals()
method.
The general contract of hashCode is:
- hashcode method should consistent. That is it should return same integer on mulitple call on same object.
- If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
- It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
Guideline for equals method.
- It is reflexive: for any non-null reference value x, x.equals(x) should return true.
- It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
- It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
- It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
- For any non-null reference value x, x.equals(null) should return false.
Source:-Hashcode Javadoc, Equals javadoc
answered Jan 1 at 7:28
TarunTarun
673414
673414
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53993657%2fhow-to-compare-objects-contained-in-the-set-what-would-be-a-good-hashcode-and-e%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Why not just use the auto-generated methods given by the IDE?
– Nicholas K
Jan 1 at 7:14
@NicholasK this is more like a leetcode exercise
– user2609410
Jan 1 at 7:23