I am having a java class Rec. I have two instance of it Rec1 and Rec2. I want to check whether the values of Rec1 and Rec2 are equal. If i do Rec1.equals(Rec2) is it correct way of doing it?
class Rec {
private BigDecimal RecordId = null;
private BigDecimal recSubNum = null;
private BigDecimal FileId = null;
private String Category = null;
private BigDecimal status = null;
private BigDecimal errorCode = null;
}
You need to implement the equals() and hashCode() methods to implement object equality in Java:
class Rec {
private BigDecimal recordId = null;
private BigDecimal recSubNum = null;
private BigDecimal FileId = null;
private String category = null;
private BigDecimal status = null;
private BigDecimal errorCode = null;
#Override
public int hashCode() {
int ret = 41;
ret = hc(ret, recordId);
ret = hc(ret, recSubNum);
ret = hc(ret, fieldId);
ret = hc(ret, category);
ret = hc(ret, status);
ret = hc(ret, errorCode);
return ret;
}
#Override
public boolean equals(Object ob) {
if (ob == null) return false;
if (ob.getClass() != Rec.class) return false;
Rec r = (Rec)ob;
if (!eq(r.recordId, record)) return false;
if (!eq(r.recSubNum, recSubNum)) return false;
if (!eq(r.fileId, fileId)) return false;
if (!eq(r.category, category)) return false;
if (!eq(r.status, status)) return false;
if (!eq(r.errorCode, errorCode)) return false;
return true;
}
private static boolean eq(Object ob1, Object ob2) {
return ob1 == null ? ob2 == null : ob1.equals(ob2);
}
private static int hc(int hc, Object field) {
return field == null ? hc : 43 + hc * field.hashCode();
}
}
Note: the equals/hashCode contract for Java means that for any two objects a and b:
a.equals(b) == b.equals(a)
and if two objects are equal then a.hashCode() must equal b.hashCode().
Edit: there are two ways of checking if the types match. Either:
if (ob == null) return false;
if (ob.getClass() != Rec.class) return false;
or
if (!(ob instanceof Rec)) return false;
These two do different things and you should select the correct one depending on what you want to do. I generally prefer the first one unless you know you need the second. What's the difference?
class A {
public int i;
public boolean equals(Object ob) {
if (!(ob instanceof A)) return false;
return i == ((A)ob).i;
}
}
Looks reasonable right? What if the class gets extended:
class B extends A {
public int j;
public boolean equals(Object ob) {
if (!(ob instanceof B)) return false;
if (!super.equals(ob)) return false;
return j == ((B)ob).j;
}
}
Still looks reasonable? It's broken.
A a = new A();
a.i = 10;
B b = new B();
b.i = 10;
b.j = 20;
System.out.println(a.equals(b)); // true! Is this really what you want?
System.out.println(b.equals(a)); // false! Different to previous = problem.
That's why I favour getClass() over instanceof unless I really want subclass equality.
if Rec is a user defined class then you really should override the equals method otherwise it will just call the equals method in the Object class;
something like :
public boolean equals(Rec x){
//check here to see if the references are the same, if so return true
if(this == x) return true;
//if they aren't the same object then check all the fields for equality
if (category.equals(x.category) && etc etc) return true;
else return false;
}
Related
I initialize the HashSet like this:
private HashSet<Rule> ruleTable = new HashSet<Rule>();
The equals() and hashCode() methods of my TcpRule object (sub-class of abstract class Rule) look like this:
#Override
public int hashCode() {
// Ignore source Port for now
return (this.getSrcPool() + ":" + this.getDstPool() + ":" + this.getProtocol() + ":" + this.dstTcp).hashCode();
}
#Override
public boolean equals(Object obj) {
if (!(obj instanceof TcpRule))
return false;
if (obj == this)
return true;
TcpRule r = (TcpRule) obj;
return (this.getSrcPool().equals(r.getSrcPool()) && this.getDstPool().equals(r.getDstPool()) && this.getProtocol().equals(r.getProtocol()) && this.getSrcTcp() == r.getSrcTcp() && this.getDstTcp() == r.getDstTcp());
}
I have even written a simple unit test, which does not give any error:
#Test
public void equalsTest() {
Pool srcPool = new Pool("PROXY");
Pool dstPool = new Pool("WEB");
int srcTcp = 54321;
int dstTcp = 80;
TcpRule r1 = new TcpRule(srcPool, dstPool, srcTcp, dstTcp);
TcpRule r2 = r1;
assert r1.equals(r2);
TcpRule r3 = new TcpRule(srcPool, dstPool, srcTcp, dstTcp);
TcpRule r4 = new TcpRule(srcPool, dstPool, srcTcp, dstTcp);
assert r3.equals(r4);
}
#Test
public void hashCodeTest() {
Pool srcPool = new Pool("PROXY");
Pool dstPool = new Pool("WEB");
int srcTcp = 54321;
int dstTcp = 80;
TcpRule r1 = new TcpRule(srcPool, dstPool, srcTcp, dstTcp);
TcpRule r2 = new TcpRule(srcPool, dstPool, srcTcp, dstTcp);
assert r1.hashCode() == r2.hashCode();
HashSet<Rule> rules = new HashSet<Rule>();
rules.add(r1);
assert rules.contains(r1);
assert rules.contains(r2);
}
In my application, I have an add() method where I simply add a Rule object to the HashSet:
#Override
public void add(Rule rule) {
ruleTable.add(rule);
}
In another method, I check if a rule exists in the HashSet:
#Override
public boolean isPermittedTcp(IpAddress sourceAddress, IpAddress destinationAddress, short srcTcp, short dstTcp) {
Pool sourcePool = poolService.getPool(new Host(sourceAddress));
Pool destinationPool = poolService.getPool(new Host(destinationAddress));
Rule r = new TcpRule(sourcePool, destinationPool, srcTcp, dstTcp);
log.info("Checking: " + r.toString());
log.info("Hash-Code: " + r.hashCode());
log.info("Hashes in ruleTable:");
for(Rule rT : ruleTable) {
log.info("" + rT.hashCode());
}
if(ruleTable.contains(r)) {
log.info("Hash found!");
} else {
log.info("Hash not found!");
}
return ruleTable.contains(r);
}
The log messages indicate that the hash of the Rule object (r.hashCode()) is -1313430269, and that one hash in the HashSet (rT.hashCode() in the loop) is also -1313430269.
But ruleTable.contains(r) always returns false. What am I doing wrong?
I have found similar questions on StackOverflow, but these mostly involve the equals() or hashCode() methods not being (correctly) overridden. I think I have implemented this two methods correctly.
Your problem is that hashCode() and equals() do not agree.
Your hashCode() implementation is based on the toString() of the pool, but your equals() uses .equals() of the pool class.
Change your .equals() to compare the strings used to generate the hash code.
There are some possibilities:
Rule is mutable, after adding a rule to the set some key (w.r.t. hash or equals) field was changed;
If two objects are equal they should have the same hashCode;
Bug, like a comparison in equals using == i.o. equals.
Here I would guess you have two Pool instances without equals on pool name or hashCode on pool name.
You have an extra condition in equals this.getSrcTcp() == r.getSrcTcp() which is not part of hash code - maybe thats the issue, hashcode is same, but equals is false. Check if this field is different in the values you are comparing.
Inspite of comments, I think the reason this does not work is because the equals & hashCode implementations do not use the same fields.
Code to simulate the problem:
import java.util.HashSet;
/**
* #author u332046
*
*/
public class HashCodeCollisionTest {
public static class KeyDemo {
String id;
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
/*if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
KeyDemo other = (KeyDemo) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;*/
return false;
}
public KeyDemo(String id) {
super();
this.id = id;
}
}
static HashSet<KeyDemo> set = new HashSet<>();
public static void main(String[] args) {
set.add(new KeyDemo("hi"));
set.add(new KeyDemo("hello"));
System.out.println(set.contains(new KeyDemo("hi")));
}
}
This prints false. Uncomment the equals code and it prints true
Have some problem with TreeSet or I just realize that it doesn't work as I expected.
I need to exclude some fields when I check if the value already exists, but on sort it should use all the fields.
It looks like TreeSet.contains() use compare or compareTo (comparator, comparable) and not equals().
Here is some example:
import java.util.Comparator;
import java.util.TreeSet;
public class sorter {
static class A {
String name;
int counter;
public A(String a, int counter) {
this.name = a;
this.counter = counter;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
A other = (A)obj;
if (name == null) {
if (other.name != null) return false;
} else if (!name.equals(other.name)) return false;
return true;
}
}
public static class MyComparator implements Comparator<A> {
#Override
public int compare(A a, A b) {
int c = b.counter - a.counter;
if (c == 0) {
return a.name.compareTo(b.name);
};
return c;
}
}
public static void main(String[] args) {
TreeSet<A> set = new TreeSet<>(new MyComparator());
set.add(new A("a", 1));
if (set.contains(new A("a", 2))) {
System.out.println("'a' already exists, do count + count");
}
}
Feels like I breaking some law here, and should re-design it in some way?
Is it possible to achieve what I try to do with a TreeSet or should I go for a simple list?
In someway I have unique items and a list doesn't feel perfect either.
Any ideas?
You could change,
public int compare(A a, A b) {
int c = b.counter - a.counter;
if (c == 0) {
return a.name.compareTo(b.name);
};
return c;
}
to be
public int compare(A a, A b) {
if (Objects.equals(a, b))
return 0;
int c = b.counter - a.counter;
if (c == 0) {
return a.name.compareTo(b.name);
};
return c;
}
This way, if they are "equal" in your sense of equal, the TreeSet will exclude them. Otherwise you sort as you wish. As a note, the Objects.equals() will do the null checking for you.
It is using comparator to find equality.
Hash based collection only used equals and hashcode for equality.
But collection like tree using comparator for equality.
If two objects are equal then compare method should return true and vice versa.
set.contains(new A("a", 2)) its false because compare method wont return true`set.contains(new A("a", 1))` will return true because that method will return true.
I would like quickly to fetch from Java Set the object equal to existing one. Is there any faster way than iterating for all elements of the set?
Here is my code:
class A {
int a,b,c,d;
public A(int a, int b, int c, int d) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + a;
result = prime * result + b;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
A other = (A) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (a != other.a)
return false;
if (b != other.b)
return false;
return true;
}
private Main getOuterType() {
return Main.this;
}
}
and in the code:
void run() {
Set<A> a = new HashSet<>();
a.add(new A(1,2,3,4));
a.add(new A(2,3,4,5));
A b = new A(1,2,3,5);
//How to fetch from set a object equal to object b?
}
Is it possible to do it fast in Groovy?
There is not get method in java.util.Set interface. Hence, you can not fetch an entry :)
Maybe you are using the wrong data structure. May be what you need is a java.util.Map?
If you already have an object then there's no point in getting it from the Set. If you like to check if it exists in the set there is http://docs.oracle.com/javase/7/docs/api/java/util/Set.html#contains(java.lang.Object)
I want to store a set of Edges:
class Edge {
int u;
int v;
char symbol;
}
The problem is that it's possible for two Edge objects to have the same u, v and symbol, but they can both be stored in a HashSet because they're not the same object even though I want them to be considered the same object. How can I store only one object that has a unique (u, v, symbol) in a Set?
You need to override the following two methods equals and hashcode.
public boolean equals(Object obj) {
if (obj == null) return false;
if (!(obj instanceof Edge)) return false;
// return true if they are the same, otherwise false
}
public int hashCode() {
// return an int that represents similarity
// Example: name.hashCode(), if they are the same with the same name
}
Depends on what kind of set you want to use; The below applies for HashSet for instance, but not for any subclass of SortedSet
By overriding equals() and hashCode():
class Edge {
int u;
int v;
char symbol;
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + symbol;
result = prime * result + u;
result = prime * result + v;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Edge other = (Edge) obj;
return symbol == other.symbol && u == other.u && v == other.v;
}
}
You have to override equals(). Like this:
public boolean equals(Object obj) {
//do the comparison here; remember to cast obj to Edge
}
I have defined a simple private class named SetOb which contains an int and a Set data structure. I have a HashMap in the 'main' method with SetOb as Key and Integer as value. Now as you can see in the main method, when I feed the HashMap with a SetOb instance and then look for an instance with exactly the same value, it returns 'null'. This has happened with me quite a few times before when I use my own defined data structures like SetOb as Key in HashMap. Can someone please point me what am I missing ?
Please note that in the constructor of SetOb class, I copy the Set passed as argument.
public class Solution {
public static Solution sample = new Solution();
private class SetOb {
public int last;
public Set<Integer> st;
public SetOb(int l , Set<Integer> si ){
last = l;
st = new HashSet<Integer>(si);
}
}
public static void main(String[] args) {
Map<SetOb, Integer> m = new HashMap< SetOb, Integer>();
Set<Integer> a = new HashSet<Integer>();
for(int i =0; i<10; i++){
a.add(i);
}
SetOb x = sample.new SetOb(100, a);
SetOb y = sample.new SetOb(100, a);
m.put(x,500);
Integer val = m.get(y);
if(val!= null) System.out.println("Success: " + val);
else System.out.println("Failure");
}
}
Your x and y are not the same object instances hence contains is not able to match y against x, which ends up not finding the matching key/value in the Map.
If you want the match to succeed, please implement(override) hasCode & equals method in SetOb which will compare the field values.
Sample methods(Eclipse generated) as below:
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + last;
result = prime * result + ((st == null) ? 0 : st.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SetOb other = (SetOb) obj;
if (last != other.last)
return false;
if (st == null) {
if (other.st != null)
return false;
} else if (!st.equals(other.st))
return false;
return true;
}
The default implementation of hashCode uses object identity to determine the hash code. You will need to implement hashCode (and equals) in your private class if you want value identity. For instance:
private class SetOb {
public int last;
public Set<Integer> st;
public SetOb(int l , Set<Integer> si ){
last = l;
st = new HashSet<Integer>(si);
}
#Override
public boolean equals(Object other) {
if (other.class == SetOb.class) {
SetOb otherSetOb = (SetOb) other;
return otherSetOb.last == last && otherSetOb.st.equals(st);
}
return false;
}
#Override
public int hashCode() {
return 37 * last + st.hashCode();
}
}
SetOb needs to override the hashCode() and thus the equals() methods.
Hash-based collections use these methods to store (hashCode()) and retrieve (hashCode()) and equals()) your objects.