I am working on a new application and I need some help on how to implement the equals method and the hashCode method. I have been reading many questions already asked here on SO, and I have also read several blog posts that has lead me to this question.
A little technical information first: I am using JPA (EclipseLink) and the application is for Java EE.
After what I have read you should use immutable values for hashCode and equals, but since the fields in the class is usually modifiable you can't use them. Nor can you use the primary key (JPA) because you won't have one before you have persisted it. So what I am thinking about is to use UUID. Both for equals and hashCode, but I have never done that before so I wonder if somebody thinks this is bad (why?) and possible downsides (apart from the tiny tiny tiny chance of getting the same ID)? Using a UUID and asign it in the constructor will give all objects a business ID from the very start. And I will make it immutable and save it to the database.
Is this approach bad?
IMO the UUID will work just fine and i would recommend doing so.
I can't find any drawbacks to this approach since the possibility of hitting 2 same values is infinitely small.
Related
I am building an application for a client and I am in the situation where I need to have the ability to reference a field value via a string, i.e the users uses a string to define which field they want to change the value of, this is part of an abstract framework so technically I don't know the name of the fields they desire to change. Of course I could do this using hash maps, but I am considering using java reflection as this allows the fields to stay as fields of the object rather than the values being coded into a hash map. I have used reflection for my own personal work, but I was wondering if using Java reflection is actually bad practice, and I should stick to the hashmap methodology.
(Any other suggestions for solving the design problem described are also appreciated)
Thanks
The question itself is opinion based, although I believe most will agree that you can't just say "reflection is bad". Sometimes it's the only way, which is why a lot of libraries use reflection. Sometimes it's not the only way, but a workaround would be even worse. Sometimes it's not the only way, and not the easiest way, but the developer is far too amazed at the power of reflection to think straight.
Except for that last one there are plenty of valid reasons to consider reflection as a solution.
Personally reflection makes me sad, and in my experience there is almost always a better way. In the problem you described, setting variables based on a string i'd consider going with your hashmap idea which would reference variables via a string key which seems like exactly what you are describing. If you need the ability to reference values that do not exist you could also include factory methods to create variables when no key exists and then add to the map, if you are wrapping the objects then they will be passed by reference to avoid the problem you describe but this depends on the implementation (eg using Integer class etc for auto boxing if you are referencing primitives) Together this would allow for a much tighter and well defined implementation rather than reflecting values here there and everywhere. Apologies for the anti-reflection bias! Hope this helps.
I would like to use a clean/automatic way to check if a Java Object has been modified.
My specific problem is the following:
In my Java application, I use XStream library to deserialize XML to Java Objects, then the user can modify or change them. I'd like a way to check if these Objects in memory are at some point different from the serialized ones, so I can inform the user and ask him if he want to save the changes (i.e. serialize using XStream) or not.
In my application there are many Objects and are quite complex.
Please consider that I don't use databases in my application, so I'm not interested in solutions like using hibernate.
Two approaches:
Implement a hashcode for your objects, and compare the hashcode of the in-memory objects against the hashcode of the serialized objects to see if they've been changed. This is has a low impact on your class design, but performance will go down as O(n^2) as the number of objects increases. Note that two objects might return the same hashcode, but a good hashing implementation will make this very unlikely. If you are concerned about this, implement and use your own equals() method.
Have your objects implement the Observer pattern and have each setter method, or any other method that modifies the object, notify the observer when it's called. Performance will be better for large numbers of objects (as long as they aren't changing constantly), but it requires you to introduce Observer code into possibly lightweight classes. Java provides a utility interface for Observable, but you'll still need to do most of the work.
You can store a version field in this object, whenever the object changed it should update its version field (increment it), you can then compare the version field with the serialized object version field
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Use cases for IdentityHashMap
What could be a practical use of the IdentityHashMap introduced in Java 5?
Have a look at the Java Docs :-)
A typical use of this class is topology-preserving object graph
transformations, such as serialization or deep-copying. To perform
such a transformation, a program must maintain a "node table" that
keeps track of all the object references that have already been
processed. The node table must not equate distinct objects even if
they happen to be equal. Another typical use of this class is to
maintain proxy objects. For example, a debugging facility might wish
to maintain a proxy object for each object in the program being
debugged.
On a side note: it's available since version 1.4, not Java 5 or 6...
For adding dynamic fields to objects.
Some language directly support dynamic fields: anybody can add any field to any object any time.
This is handy when you want to associate some information to objects, unforseenable by object designer.
Java doesn't have real dynamic field. We can simulate it by using an identity map to associate an object to some information of some kind.
WeakHashMap is better for the purpose; it is an identity map too, and it doesn't add additional strong reference to the object. So it is much closer to the dynamic field concept.
Concurrency is the remaining problem. If two threads accessing the same dynamic field of two different objects, there shouldn't be dependencies among two threads. We can solve it by some kind of concurrent weak hashmap. However the performance isn't ideal compared to normal field access.
Think about java.lang.ThreadLocal, adding dynamic field to threads; and java.lang.ClassValue, adding dynamic field to classes. They aren't strictly necessary - we can achieve the same thing with concurrent weak maps. They exist for performance reason. JDK can "hack" into Thread/Class to add supports to achieve faster lookup.
When serializing mutable objects you want to keep track of the objects you have serialized and their reference id. You cannot use equality as you cannot trust mutable objects to use identity checks for equals and to not change. e.g. Date is mutable and equals compares contents.
Used rarely. It implements Map interface but used in rare cases wherein reference-equality semantics are required.
Given an object we will call loc that simply holds 2 int member values, I believe I need to come up with a mechanism to generate a hashcode for the object. What I tried below doesn't work as it uses an object reference, and the 2 references will be different despite having the same members variables.
Map<Loc,String> mapTest = new HashMap<Loc,String>();
mapTest.put(new Loc(1,2), "String 1");
mapTest.put(new Loc(0,1), "String 2");
mapTest.put(new Loc(2,2), "String 3");
System.out.println("Should be String 2 " + mapTest.get(new Loc(0,1)));
After some reading it seems I need to roll my own hashcode for this object, and use that hashcode as the key. Just wanted to confirm that I am on the right track here, and if someone could guide me to simple implementations to look at that would be excellent.
Thanks
Yes, you need to override equals() and hashCode() and they need to behave consistently (that is, equal objects have to have the same hash code). No you do not use the hash coe directly; Map uses it.
Yes, you're on the right track.
See articles like this for more details.
There are a lot of different ways to implement a hashcode, you'll probably just want to combine the hashcodes of each integer primitive.
Writing correct equals and hashcode methods can be tricky and the consequences of getting it wrong can be subtle and annoying. If you are able to, I would use the apache commons-lang library and take advantage of the HashCodeBuilder and EqualsBuilder classes. They will make it much easier to get the implementations right. The benefit of using these libraries is that it is much harder to get the boiler plate wrong, they hide the visual noise these methods tend to create and they make it harder for someone to come a long later and mess it up. Of course another alternative is to let your IDE generate those methods for you which works but just creates more of the noisy code vomit Java is known for.
If you want to use your type as a key type in a map, it's essential that it provides sane implementations of equals and hashCode. Fortunately, you don't have to write these implementations manually. Eclipse (and I guess other IDEs as well) can generate this boilerplate for you. Or you can even use Project Lombok for that.
Ideally the object to be used as a key in a map should be immutable. This can save you from many bugs led to by the equality issues in the context of mutation.
You need to implement both hashCode() and equals(). Joshua Bloch's Effective Java should be the definitive source on the "how" part of your question, and I'm not sure if it's okay to reproduce it here, so I'll just refer you to it.
After reading this article , im bending toward not overriding equals() and hashCode() altogether.
In the summary of that article, concerning the no eq/hC at all column, the only consequence is that i couldnt do the comparison operations like :
contains() in a List for detached entities, or
compare the same entities from different sessions
and expect the correct result.
But im still in doubt and would like to ask your experiences about this whether it is a bad practice to skip equals and hashCode altogether and what other consequences that i still dont know for now.
Just another point of information, im bending towards using List Collections over Set. And my assumption is that i dont really need to override hashCode and equal when storing in a List.
Read this very nice article on the subject: Don't Let Hibernate Steal Your Identity.
The conclusion of the article goes like this:
Object identity is deceptively hard to implement correctly when
objects are persisted to a database. However, the problems stem
entirely from allowing objects to exist without an id before they are
saved. We can solve these problems by taking the responsibility of
assigning object IDs away from object-relational mapping frameworks
such as Hibernate. Instead, object IDs can be assigned as soon as the
object is instantiated. This makes object identity simple and
error-free, and reduces the amount of code needed in the domain model.
whether it is a bad practice to skip equals and hashCode altogether
Yes. You should always override your equals and hashCode. Period. The reason is that this method is present already in your class, implemented in Object. Turns out that this implementation is generic, and nearly 100% of the times it's a wrong implementation for your own objects. So, by skipping equals/hashCode you are in fact providing a wrong implementation and will (in the best case scenario) confuse whoever uses these classes. It may be your colleagues, or it may be some framework you are using (which can lead to unpredictable and hard-to-debug issues).
There's no reason to not implement these methods. Most IDEs provides a generator for equals/hashCode. You just need to inform the IDE about your business key.
You got the exact opposite conclusion from that article of what it was trying to convey.
Hibernate heavily relies on equals being implemented properly. It will malfunction if you don't.
In fact, almost everything does; including standard java collections.
The default implementation does not work when using persistence. You should always implement both equals and hashcode. There's a simple rule on how to do it, too:
For entities, use the key of the object.
For value objects, use the values
Always make sure the values you use in your equals/hashcode are immutable. If you pass these out (like in a getter), preferably pass them out in an immutable form.
This advice will improve your life :)