Object identity and equality identical in-memory object instances. (Web hosting uk)

Object identity and equality identical in-memory object instances. This can lead to problems if you treat them as equal in detached state. For example, consider the following extension of the code, after session2 has ended: … session2.close(); Set allObjects = new HashSet(); allObjects.add(a); allObjects.add(b); allObjects.add(c); All three references have been added to a Set. All are references to detached objects. Now, if you check the size of the collection, the number of elements, what result do you expect? First you have to realize the contract of a Java Set: No duplicate elements are allowed in such a collection. Duplicates are detected by the Set; whenever you add an object, its equals() method is called automatically. The added object is checked against all other elements already in the collection. If equals() returns true for any object already in the collection, the addition doesn t occur. If you know the implementation of equals() for the objects, you can find out the number of elements you can expect in the Set. By default, all Java classes inherit the equals() method of java.lang.Object. This implementation uses a double-equals (==) comparison; it checks whether two references refer to the same in-memory instance on the Java heap. You may guess that the number of elements in the collection is two. After all, a and b are references to the same in-memory instance; they have been loaded in the same persistence context. Reference c is obtained in a second Session; it refers to a different instance on the heap. You have three references to two instances. However, you know this only because you ve seen the code that loaded the objects. In a real application, you may not know that a and b are loaded in the same Session and c in another. Furthermore, you obviously expect that the collection has exactly one element, because a, b, and c represent the same database row. Whenever you work with objects in detached state, and especially if you test them for equality (usually in hash-based collections), you need to supply your own implementation of the equals() and hashCode() methods for your persistent classes.
We highly recommend you visit web and email hosting services if you need stable and cheap web hosting platform for your web applications.