I'm making a 2D game that has a stars in it. I decided to create constructor in class named Star that gives random coordinates.
public Star(){
super(0,0);
x = randomX.nextInt(maxX - minX + 1);
y = randomY.nextInt(maxX - minY + 1);
}
Then, in other class I put them in HashSet
Set<Star> star = new HashSet<>();
public Set<Star> generateStars(){
while (star.size() < numberOfStars){
star.add(new Star());
}
return star;
}
Of course, I have render and tick methods but I think it's not worth to paste them. My lecturer told me that there can be same stars and to prevent that I should use identity function using hashcodes. Can someone help me figure that out ? I imagine that this function should check if the hashcodes are the same and if it's the case it should return only one value that way we will add 1 object instead of 2 into the HashSet. Am I right ?
Overriding the hashCode() method alone in your Star class will not work you will have to override the equals() method.
See the following code where we don't override the equals() method:
class Star {
int x, y;
public Star(int x, int y) {
this.x = x;
this.y = y;
}
#Override
public int hashCode() {
return Objects.hash(x, y);
}
}
public class Main {
public static void main(String[] args) {
Star s1 = new Star(0, 0);
Star s3 = new Star(0, 0);
Star s2 = new Star(31, -31*31);
Set<Star> set = new HashSet<>();
set.add(s1);
set.add(s2);
System.out.println(set.size());
}
}
This will print 3 (instead of 2 what you might expect).
The reason for this is that the add method of java.util.Set compares 2 objects based on equals() method and not based on hashCode() method.
In the above code for the Star class, if you add the equals() method the output will be 2 now. For your reference the you can override the equals() method as follows:
#Override
public boolean equals(Object startObject) {
if (this == startObject) return true;
if (startObject == null || getClass() != startObject.getClass()) return false;
Star star = (Star) startObject;
return x == star.x &&
y == star.y;
}
So why do you need to add hashCode()?
As you are using HashSet the add method behind the scene will call the equals() method and will also call hashCode() to decide the bucket in which the new object should be put. To maintain the contract of hashCode() and equals() Both should be overridden.
When ever you override equals(), it is recommended to override hashCode() also. (Vice-versa is also true). See this link for details.
Contract for hashCode() and equals(): If for two objects say o1 and o2, o1.equals(o2) is true then hash of o1 and o2 should be same.
Make sure that you understand this properly, from the above statement it is not implied that if the hash of 2 objects are same, then o1.equals(o2) should return true. It can be possible that for 2 objects, their hash is same but the o1.equals(o2) returns false
See here, what Object's hashCode() method guarantees.
See this link to get more detailed information about this topic.
In java, when adding an object to a HashSet, the add method uses the 'equals' method, which is part of the Object class (however you can override it) in order to determine if the set already contains the object you are trying to add, see : https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html
However, if you are overriding the equals method then you should also override the hashCode method, this is very well explained in the following post : Why do I need to override the equals and hashCode methods in Java?
If you are going to follow this advice, I would also advise using ApacheCommonsLang EqualsBuilder and HashCodeBuilder if your lecturer allows it as they provide a solid implementation based on the rules laid out in the book 'Effective Java' by Joshua Bloch
To override the equals method in your Star class, you want to think about the criteria that make two star objects equal. From your example this might be that both of them have the same x and y co-ordinates.
you can override hashCode() method from Object. So, in your Star class, add:
#Override
public int hashCode() {
in hash = .... //make your hash code about the coordinates of your star.
return hash;
}
so, when you place a new star with the same co-ordiante in the hash map, it will overwrite the previous start with the same co-ordiantes if already present in the map.
You have to implement hashCode and equals.
the code should be like this:
public static class Star {
int x, y;
public Star(int x, int y) {
this.x = x;
this.y = y;
}
#Override
public int hashCode() {
return x * 1000 + y;
}
#Override
public boolean equals(Object obj) {
if (obj instanceof Star) {
Star s = (Star) obj;
return this.x == s.x && this.y == s.y;
}
return false;
}
}
public static void main(String args[]) throws Exception {
HashSet<Star> set = new HashSet<Star>();
set.add(new Star(1, 1));
set.add(new Star(1, 1));
System.out.println(set.size());
}
note: choose the suitable hashcode function for you. I assumed here that y should always be less than 1000.
If you are using eclipse as your editor just right-click on the editor pane, go-to source then generate hashcode() and equals() pick the parameters you would like to consider. You will get an autogenerated function.
Related
Hi i'm just beginner learning about abstract classes & interfaces.
Everything we build our prof is testing by creating clones and comparing objects.
I've learned overriding the equals() method the detailed way…
#Override
public boolean equals(Object obj){
if (this == obj){
return true;
}
else if (obj == null){
return false;
}
...
else {
Obj x = (*Superclass*)obj;
…
}
I was now wondering if I could replace this long way by a short Version where I change the toString method, do a hashCode of the toString method and compare the hashCodes of my Objects (original & clone).
Would this be ok to do or is there any reason i shouldn't do it?
Would I be able to inherit the toString, hashCode and equals method and just adjust the clone() in subclasses if we assume that the subclasses use the same variables?
My idea was following
public abstract *Superclass*{
public String name; //would be private in org. code
public int hp; //would be private in org. code
public Superclass(){
}
#Override
public Superclass clone(){
return this; //(not sure if this is ok to use)
}
#Override
public String toString(){
Class temp = getClass();
return temp.getName() + this.name + " " + this.hp;
}
#Override
public int hashCode(){
int hcModify = 10;
int hcCurrent = this.toString().hashCode();
return hcModify * hcCurrent;
}
#Override
public boolean equals(Object obj){
return this.hashCode() == obj.hashCode())
}
}
So the first thing to note is that your equals method will throw an error if obj is null - you can't use any . operators on null.
Your clone method is dangerous if there's mutability in play - mutability means "values can be changed". Because it just returns a reference, changes will be reflected in both the original and "cloned" values (because they're the same.) This is not what most developers would expect. (I suggest looking up deep vs. shallow clones, which is related.)
x = new Thing()
y = thing.clone()
x.changeInSomeWay()
//is y now also changed?
The method of using hash codes for equality is not necessarily good or bad - it depends on the relation of the object to its hash and toString functions, and if there are colisions. Some objects will have hash or toString colisions, where different objects will have the same hash or string representations - particularly large or complex objects, where those representations don't include all of the data that you'd want to be reflected in an equality check.
Yours is actually an example of this. You're using an int hashcode, which only has 2^32 (or whatever) possible values, while Strings have, in principle, infinite possible values; by the pigeonhole principal, there must therefor be multiple objects with different names but the same hashcode.
In general, it's not a safe practice, and can lead to weird, difficult to diagnose errors.
I'm not sure why you're multiplying by 10?
According to the official documentation for the Java Hashtable class (https://docs.oracle.com/javase/7/docs/api/java/util/Hashtable.html), the get() opperation will return one of it's recorded values, if said value has a key that returns true when the parameter is fed into that key's equals() opperation.
So, in theory, the following code should return "Hello!" for both of the Hashtable's get() queries:
public static class Coordinates implements Serializable {
private int ex;
private int why;
public Coordinates(int xCo, int yCo) {
ex = xCo;
why = yCo;
}
public final int x() {
return ex;
}
public final int y() {
return why;
}
public boolean equals(Object o) {
if(o == null) {
return false;
} else if(o instanceof Coordinates) {
Coordinates c = (Coordinates) o;
return this.x() == c.x() && this.y() == c.y();
} else {
return false;
}
}
}
Hashtable<Coordinates, String> testTable = new Hashtable<Coordinates, String>();
Coordinates testKey = new Coordinates(3, 1);
testTable.put(testKey, "Hello!");
testTable.get(testKey); //This will return the "Hello" String as expected.
testTable.get(new Coordinates(3, 1)); //This will only return a null value.
However, get() doesn't work as it's supposed to. It seems to only work if you litterally feed it the exact same object as whatever was the original key.
Is there any way to correct this and get the Hashtable to function the way it's described in the documentation? Do I need to make any adjustments to the custom equals() opperation in the Coordinates class?
To be able to store and retrieve objects from hash-based collections you should implement/oeverride the equals() as well as hashCode() methods of the Object class. In your case, you have overridden the equals() and left the hashCode() method to its default implementation inherited from the Object.
Here is the general contract of the hashCode() method you must consider while implementing it:
Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
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.
And here is an example implementation that is generated from my IDE (as alread mentioned by #Peter in the comment area) which you can modify to suit your requirements:
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ex;
result = prime * result + why;
return result;
}
class Object{
String x;
int y;
Object (String a, int b){
this.x = a;
this.y = b;
#Override
boolean equals(Object obj){
return (this.x.equals(obj.x)) && this.y == obj.y);
}
}
Here I am trying to write a method that overrides equals() in order to equate two values, a string and an integer, at the same time. In order to test for string equality, I use the original equals() method that I am overriding.
Can I do this without errors? Or can I not use the original equals() method inside of a method overriding it? Is there a better way of achieving this?
I am not quite able to find answers to this question online, but that may be a result of not knowing the technical wording for a situation like this.
Thank you
I think the problem is that you're not correctly overriding the Object.equals() method. If you're trying to check that both the String and the int are equal in order for your object to be equal, it sounds like you want a new object to represent whatever the String and int together represent:
class MyObj {
private String str;
private int num;
...
}
(with appropriate getter and setter methods)
Then you can override MyObj.equals() like so:
#Override
boolean equals(MyObj that){
/* First check for null and all that stuff */
...
return this.str.equals(that.getStr()) && this.num == that.getNum();
}
Call:
super.whatevername();
Or in this case:
super.equals(someObject);
This will call the superclass' method
By the way, the original method for equals is
public boolean equals(Object obj)
By the way, your whole return block can be replaced by:
return (this.x.equals(obj.x)) && this.y == obj.y);
The way you did it is inefficient and makes me cringe :/
This question already has answers here:
What issues should be considered when overriding equals and hashCode in Java?
(11 answers)
Closed 4 years ago.
I did this test in a HashSet comparision and equals is not being called
I would like to consider equals when farAway=false
(A function to check two point distances)
Full compilable code, you could test it, and tells why equals is not being called in this example.
public class TestClass{
static class Posicion
{
private int x;
private int y;
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Posicion other = (Posicion) obj;
if ( farAway(this.x, other.x, this.y, other.y,5)){
return false;
}
return true;
}
#Override
public int hashCode() {
int hash = 7; hash = 59 * hash + this.x; hash = 59 * hash + this.y;
return hash;
}
Posicion(int x0, int y0) {
x=x0;
y=y0;
}
private boolean farAway(int x, int x0, int y, int y0, int i) {
return false;
}
}
public static void main(String[] args) {
HashSet<Posicion> test=new HashSet<>();
System.out.println("result:"+test.add(new Posicion(1,1)));
System.out.println("result:"+test.add(new Posicion(1,2)));
}
}
EDIT
-Is there a way to force HashSet add to call equals?
If the hash codes differ, there is no need to call equals() since it is guaranteed to return false.
This follows from the general contract on equals() and hashCode():
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.
Right now your class is breaking that contract. You need to fix that.
If you want equals() to be called always, just always return, say, 0 in hashCode(). This way all items have the same hash code and are compared purely with equals().
public int hashCode() {
return 0;
}
It sounds like HashSet isn't right for you.
It sounds like you want a custom way of comparing two positions. Rather than saying "are two positions exactly equal?".
Instead, you should look at using TreeSet, with a Comparator. This way, you can write a "IsWithinRangeComparator" and do your range checking there.
As suggested above,when objects are equal, their hashcode should also be the same.
You could make a simple fix to your hashcode computation like below.
public int hashCode() {
int hash = 7; hash = 59 * hash + this.x; hash = 59 * hash + this.y;
boolean faraway=farAway(this.x, other.x, this.y, other.y,5);
hash=59*hash+(faraway?1:0); //include faraway also as part of hashcode computation
return hash;
}
I have a problem when retrieving values from a hashmap. The hashmap is declared as follows:
HashMap<TRpair,A> aTable = new HashMap<TRpair,A>();
I then put 112 values into the map as follows:
aTable.put(new TRpair(new T(<value>),new Integer(<value>)),new Ai());
where Ai is any one of 4 subclasses that extend A.
I then proceed to check what values are in the map, as follows:
int i = 0;
for (Map.Entry<TRpair,A> entry : aTable.entrySet()) {
System.out.println(entry.getKey().toString() + " " + entry.getValue().toString());
System.out.println(entry.getKey().equals(new TRpair(new T("!"),new Integer(10))));
i++;
}
i holds the value 112 at the end, as one would expect and the equality test prints true for exactly one entry, as expected.
However, when I do
System.out.println(aTable.get(new TRpair(new T("!"), new Integer(10))));
null is output, despite the above code snippet confirming that there is indeed one entry in the map with exactly this key.
If it helps, the class TRpair is declared as follows:
public class TRpair {
private final T t;
private final Integer r;
protected TRpair(Integer r1, T t1) {
terminal = t1;
row = r1;
}
protected TRpair(T t1, Integer r1) {
t = t1;
r = r1;
}
#Override
public boolean equals(Object o) {
TRpair p = (TRpair)o;
return (p.t.equals(t)) && (p.r.equals(r));
}
#Override
public String toString() {
StringBuilder sbldr = new StringBuilder();
sbldr.append("(");
sbldr.append(t.toString());
sbldr.append(",");
sbldr.append(r.toString());
sbldr.append(")");
return sbldr.toString();
}
}
the equals() and toString() methods in each of the Ai (extending A) and in the T class are overridden similarly and appear to behave as expected.
Why is the value output from the hashmap aTable null, when previously it has been confirmed that the value for the corresponding key is indeed in the map?
With many thanks,
Froskoy.
The keys/elements for a Hash collection but override hashCode() if euqals is overridden.
You could use.
public int hashCode() {
return t.hashCode() * 31 ^ r.hashCode();
}
BTW: It appears from your code that Integer r cannot be null in which case using int r makes more sense.
From Object.equals()
Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.
IIRC hashmap looks up by hashCode() and not by equality, and since you did not implemented hashcode you use default implementation which is consistent with object pointer equality -
you need to implement proper hashcode function which takes into account "T" parameter as well as integer (or not)
It is good practice that hashCode() and equals() are consistent, but not structly necessary if you know what you are doing.