How to comapre two list of hibernate entities are equal - java

I have list of 2 hibernate entities.
I need to compare them. When I use equals() it always gives false as its reference is different.
E1.equals(E2)

It's because you're taking a reference to the List object only when evaluating equality. You would have to iterate through the collections to check (assuming the ordering is important):
E1.size() == E2.size() && IntStream.range(0, E1.size())
.allMatch(index -> E1.get(index).equals(E2.get(index)));
P.S.1: Variable names are written lowercase in java.
P.S.2: Make sure you're defining equals and hashCode properly. By default same entity is not equal in different states (managed, detached).

Related

How can I take into consideration the object itself when calculating a hash for an object in Java?

I was working on some algorithmic problems when I got to this and it seemed interesting to me. If I have two lists (so two different objects), with the same values, the hashcode is the same. After some reading, I understand that this is how it should behave. For example:
List<String> lst1 = new LinkedList<>(Arrays.asList("str1", "str2"));
List<String> lst2 = new LinkedList<>(Arrays.asList("str1", "str2"));
System.out.println(lst1.hashCode() + " " + lst2.hashCode());
...........
Result: 2640541 2640541
My purpose would be to differentiate between lst1 and lst2 in a list for example.
Is there a structure (like a HashSet for example) that takes into consideration the actual object and not only the values inside the object when calculating the hashcode for something?
Yes, you can use java's java.util.IdentityHashMap, or guava's identity hash set.
The hashes of the two lists must be equal, because the objects are equal. But the identity map and set above are based on the identity of the list objects, not their hash.
If I have two lists (so two different objects), with the same values, the hashcode is the same. After some reading, I understand that this is how it should behave.
Yes, this is part of the specification of java.util.List.
Is there a structure (like a HashSet for example) that takes into consideration the actual object and not only the values inside the object when calculating the hashcode for something?
My purpose would be to differentiate between lst1 and lst2 in a list for example
It is unclear what "in a list" means here. For example, Collection.contains() and List.equals() are defined in terms or members' equals() methods, and likewise the behavior of List.remove(Object). Although distinct objects, your two Lists will compare equal to each other, so those methods will not distinguish between them, neither directly nor as members of another list. You can always compare them for reference equality (==), however, to determine that they are not the same object despite being equals() each other.
As far as a collection that takes members' object identity into account, you could consider java.util.IdentityHashMap. Two such maps having keys and associated values that are pairwise equals() each other but not identical will not compare equals() to each other. Such sets will typically have different hash codes than each other, though that cannot be guaranteed. Note well, however, the warnings throughout the documentation of IdentityHashMap that although it implements the Map API, many of the behavioral details are inconsistent with the requirements of that interface.
Note also that
most of the above is relevant only for collections whose members are of a type that overrides equals() and hashCode(). The implementations of or inherited from Object differentiate between objects on a reference-equality basis, so the ordinary collections classes have no surprises for you there.
identical string literals are not required to represent distinct objects, so the lst1 and lst2 in your example code may in fact contain identical elements, in the reference equality sense.
Not generally in collections, because you generally want two collections with all the same items to be equal (which is why they implement it like this- equals will return true and the hash codes are the same).
You can subclass a list and have it not do that, it would just not be widely useful and would cause a lot of confusion if other programmers read your code. In that case, you'd just want equals to return the result of == and hashCode to return the integer value of the reference (the same thing that Object.equals does).

Java - Best way to compare two Sets by hashes (via ==)

I have two Sets of Strings. Strings are the same (== returns true). I believe that comparing via == should be faster than comparing via equals() or hashCode(). So how to make sure they are the same not using equals()? Thanks
Since the two Sets are not the same instance, you can't use == to compare the Sets.
Now, if you use Set's equals, it (and by "it" I mean the default implementation of AbstractSet) will validate the two Sets have the same size and then iterate over the elements of one Set and check if the other Set contains each of them.
If, for example, you are using HashSets, in order to find if a String is contained in some HashSet, hashCode() will have to be used to find the bucket that may contain the searched String, but later String's equals() will be called to validate the presence of a String equal to the searched String. String's equals() actually begins with
if (this == anObject) {
return true;
}
so the fact that your two Sets may contain references to the same String instance will be helpful in improving the runtime of the Sets comparison.

How to assert that lists are equal with testng?

I found an answer for junit, but need a solution for testng. Any ideas more usefull as writing an own for loop?
There's no need for a separate method for List comparison. Two lists can be compared by org.testng.Assert#assertEquals(Object, Object).
If two lists a and b are non-null, the call Assert.assertEquals(a, b) means a.equals(b) will be called subsequently.
And java.util.List#equals is what you need, as described in javadoc:
Compares the specified object with this list for equality. Returns
true if and only if the specified object is also a list, both lists
have the same size, and all corresponding pairs of elements in the two
lists are equal. (Two elements e1 and e2 are equal if (e1==null ?
e2==null : e1.equals(e2)).) In other words, two lists are defined to
be equal if they contain the same elements in the same order. This
definition ensures that the equals method works properly across
different implementations of the List interface.

General contract for object comparision : equals() and hashCode()

There is a point in general contract of equals method, which says if You has defined equals() method then You should also define hashCode() method. And if o1.equals(o2) then this is must o1.hashCode() == o2.hashCode().
So my question is what if I break this contract? Where can bring fails the situation when o1.equals(o2) but o1.hashCode != o2.hashCode() ?
It will lead to unexpected behavior in hash based data structure for example: HashMap, Read how HashTable works
HashMap/HashTable/HashSet/etc will put your object into one of several buckets based on its hashCode, and then check to see if any other objects already in that bucket are equal.
Because these classes assume the equals/hashCode contract, they won't check for equality against objects in other buckets. After all, any object in another bucket must have a different hashCode, and thus (by the contract) cannot be equal to the object in quesiton. If two objects are equal but have different hash codes, they could end up in different buckets, in which case the HashMap/Table/Set/etc won't have a chance to compare them.
So, you could end up with a Set that contains two objects which are equal -- which it's not supposed to do; or a Map that contains two values for the same one key (since the buckets are by key); or a Map where you can't look up a key (since the lookup checks both the hash code and equality); or any number of similar bugs.
If you break the contract, your objects won't work with hash-based containers (and anything else that uses hashCode() and relies on its contract).
The basic intuition is as follows: to see whether two objects are the same, the container could call hashCode() on both, and compare the results. If the hash codes are different, the container is allowed to short-circuit by assuming that the two objects are not equal.
To give a specific example, if o1.equals(o2) but o1.hashCode() != o2.hashCode(), you'll likely be able to insert both objects into a HashMap (which is meant to store unique objects).

Difference between the two Java operators: != vs !equals

Is this code:
elem1!=elem2
equivalent to this one?
!elem1.equals(elem2)
It compiles both ways, but I'm still unsure about it...
== (and by extension !=) check for object identity, that is, if both of the objects refer to the very same instance. equals checks for a higher level concept of identity, usually whether the "values" of the objects are equal. What this means is up to whoever implemented equals on that particular object. Therefore they are not the same thing.
A common example where these two are not the same thing are strings, where two different instances might have the same content (the same string of characters), in which case a == comparison is false but equals returns true.
The default implementation of equals (on Object) uses == inside, so the results will be same for objects that do not override equals (excluding nulls, of course)
In general, no they're not the same. The first version checks whether elem1 and elem2 are references to the same object (assuming that they're not primitive types). The second version calls a type-specific method to check whether two (possibly distinct) ojects are "equal", in some sense (often, this is just a check that all their member fields are identical).
I don't think this has anything to do with generics, as such.

Categories

Resources