Objectmodel equals() and hashCode()

Hello,
all my objects have a db-id:
class Emp {
private Long id;
Now i have overridden the equals()-method like this:
public boolean equals(Object obj) {
if (obj instanceof Emp) {
if (((Emp)obj).getId().equals(id)) {
return true;
return false;
and the hashCode()-method like this:
public int hashCode() {
return id.intValue() * 17;
I wonder what I should do with new objects, cos the id is null until a commit updated the cache-object. Any suggestion on this?
Steffen

equals is a business level definition. In the case where the id is null, you'll need to make the comparison on whatever fields you feel are necessary in your business domain. It may require doing comparisons on other fields, etc. Or, since an object with a null id is obviously new and uncommitted, you may be able to assume it's not .equals to anything else. It really depends on your business domain and where/how you're using it.
- Don

Similar Messages

  • Adding Objects To a HashSet, overriding equals and hashCode

    Hi everyone,
    I'm trying to add objects to a HashSet, using a string identifier (an attribute of these objects) to determine if two objects are equal.
    I have a class 'IntExpEvent' class that overrides the equals and hashCode methods.
    public class IntExpEvent implements ExperimentalEvent{
    public int correctAnswer;
    public String identifier;
    public IntExpEvent(String id, int correctAnswer){
         this.identifier = id;
         this.correctAnswer=correctAnswer;
    public String getID(){
         return(this.identifier);
    public boolean equals(ExperimentalEvent e){
         return (this.identifier.equals(e.getID()));
    public int hashCode(){
         System.out.println((this.getID()).hashCode());
         return (this.getID()).hashCode();
    private int hashCode=-1;
    public int hashCode() {
         if(hashCode==-1) {
         char[] ca=getID().toCharArray();
         for(int x=0;x<ca.length;x++) {
              hashCode+=ca[x];
         return(hashCode);
         IntExpEvent e1 = new IntExpEvent("test_IntExpEvent",4);
         IntExpEvent e2 = new IntExpEvent("test_IntExpEvent",6);
         HashSet hs = new HashSet();
         System.out.println(hs.add(e1));
         System.out.println(hs.add(e2));
    I can still add both e1 and e2 to the HashSet, which is what I'm trying to stop from happening. i.e. objects with the same identifier should be treated as the same object, allowing only one to be added to the HashSet. Does anyone know how I can do this? Help would be greatly appreciated

    In fact you don't override the equals method. The signature defined in the Object class is
      boolean equals(Object o)In your case it is
      boolean equals(ExperimentalEvent e)So instead of overriding the method you're overloading it.
    Regards

  • Why methods equals() and hashCode() is defined in Object Class?

    Why methods equals() and hashCode() is defined in Object Class?

    If you have two objects and you don't know (or care about) their exact types, but you still want to know if they are the same, then you can do something like this:
    Object o1 = getObject1();
    Object o2 = getObject2();
    if (o1.equals(o2)) {
      // they are the same, do something
    } else {
      // they are different, do something else
    }This could be useful if you were to write a generic cache, for example.
    A similar thing is true for hashCode(), if you want to manage things in a HashSet, you'll need them to implement hashCode().
    If Object didn't have those methods, then you'd have to write that code against a more specific interface/class and it wouldn't be so general any more.

  • Overrideing equals() and hashCode()

    This is related to my previous post. I have followed the advice that was given to me. I overrode equals() and hashcode()
    public class TwoTuple<A,B>{
         public final A first;
         public final B second;
         public TwoTuple(A a, B b){
              first = a;
              second = b;
         public boolean equals(TwoTuple tt){
            return first.equals(tt.first);
         public int hashCode(){
              return 31 * first.hashCode();
         public String toString(){
              return "Variable == " + first + "  Value == " + second;
    }Test class:
    import java.util.*;
    public class Test{
         private static Set<TwoTuple> state = new HashSet<TwoTuple>();
         public static void main(String[] args){
              state.add(new TwoTuple<String,Boolean>("Testing", true));
              state.add(new TwoTuple<String,Boolean>("Testing", true));
              state.add(new TwoTuple<String,Boolean>("Testing", true));
              for(TwoTuple tt : state){
                   System.out.println(tt);
              TwoTuple tt = new TwoTuple("Testing", true);
              System.out.println("Equals == " + tt.equals(new TwoTuple("Testing", true)));
              System.out.println("Equals == " + tt.equals(new TwoTuple("Hello", true)));
              System.out.println("Equals == " + tt.equals(new TwoTuple("abc", true)));
    }Output;
    Variable == Testing  Value == true
    Variable == Testing  Value == true
    Variable == Testing  Value == true
    Equals == true
    Equals == false
    Equals == falseI am still getting 3 elements that are identical inside my set. What am I doing wrong?

    SquareBox wrote:
    This is related to my previous post.An unrelated piece of advice that I was going to put in your previous thread (but it seems you've moved on):
    Be careful how you name your classes.
    'TwoTuple' may mean something to you, but it's not very descriptive to the rest of us. Furthermore, the word 'Tuple' suggests a very specific usage that isn't borne out in any of the methods you've implemented. What about 'Pair' or 'Couple' or 'Duo'? (In the world of names, shortest is usually best.)
    Winston

  • Overriding equals and hashCode

    Everywhere I look it talks about overriding equals and hashCode together, and it also warns that doing it wrong could complicate things severly. However I haven't been able to find good documentation on how to do it properly.
    Any suggestions on where to find this out, or how to properly override the two?

    Thank you!!
    I have to say I have been very impressed with this forum. I have posted on many java forums recently with little or no success. This forum has been great, I normally get responses if a few minutes and they are all very helpful.
    thanks again

  • Comparator question - changing Equals and HashCode too?

    Hi all I have an object test - this contains 2 variables:
    Int a; and Int b;Then there is a method called test() which returns a double and looks like this:
    public Double test()
    return a * (1d / b);
    }I have implemented the compareTo method do the "compareTo" test using the call to test() not on the fields directly e.g.
    this.test().compareTo(anotherObject.test()) instead of
    if (this.a != null && anotherDateInterval.a != null)
                compareTo = this.a.compareTo(anotherDateInterval.a);
            }Because I using the test() in the compareTo do I need to change the equals and hashcode method as well to reflect the use of test()?
    e.g.
    public boolean equals(Object obj)
       if (test() == null)
                if (other.test() != null)
                    return false;
            else if (!test().equals(other.test()))
                return false;
    }

    That depends if there are any class invarients that can be depended upon.
    The basic rule is that if .equals() returns true, then .compareTo() must return 0, but not necessarily the other way around. As long as this holds true, you don't really have to change .equals() or .hashCode(). If you're still using the identity equals method, then you probably don't have to worry about it. If you've overridden .equals() to be dependent upon a and b in some way, you probably do have to change the way .equals() works to make sure that .equals() doesn't return true if .compareTo() doesn't return 0.
    - Adam

  • HashSet - equals and hashCode

    I must be missing the obvious over here..from what I understood of HashSet's/equals and hashCode, the program below should not add the Person object twice. Please suggest whats wrong...
    import java.util.*;
    public class TestHashSet2 {
    Set set = null;
    public TestHashSet2() {
    set = new HashSet();
    class Person {
    String name;
    Person(String name) {
    this.name = name;
    public boolean equals(Person person) {
    if (name.equals(person.name)) {
         return true;
    } else {
         return false;
    public int hashCode() {
    int code = name.length();
    System.out.println(" HashCode: " + code);
    return code;
    public void addPerson() {
    Person person1 = new Person("Mike");
    set.add(person1);
    Person person2 = new Person("Mike");
    System.out.println(" person1 equals person2: " + person1.equals(person2));
    set.add(person2);
    public void showPersons() {
    Iterator iterator = set.iterator();
    Object obj = null;
    while (iterator.hasNext()) {
    obj = iterator.next();
    System.out.println(" ELEMENT--> " + obj);
    System.out.println(" Number of elements in set: " + set.size());
    public static void main(String args[]) {
    TestHashSet2 tSet = new TestHashSet2();
    tSet.addPerson();
    tSet.showPersons();
    }

    the method equals(Person) has a different parameter type as equals(Object) and therefore doesn't override it. You need to change the method to equals(Object). This is a common 'gotcha' ...

  • Why Collection interface declares equals() and hashCode() method

    When I went through the source code of Collection interface, I found equals() and hashCode() are declared? Why? If a class implements this interface, it will inherit these two method from Object, and we can true to override them.

    It's probably so that they can provide the documentation that you see there.

  • WebLogic 10.3 doesn't implements equals() and hashCode() for TimerHandle?

    Hi,
    I'm using WebLogic 10.3 and need to use TimerHandle to handle some logic in my application.
    Below is a scenario.
    At the time by creating EJB Timer, I've saved the TimerHandle for later use into Database along with specific name as a key.
    Then, at the time to execute/awaken timer I need to check that the saved TimerHandle is the same as passed Timer.
    @Timeout
    public void execute( final Timer timer )
    // getting key from passed object in timer.getInfo().
    // getting saved timerhandle by key. let's say dao.getXxxHandle(key);
    // perform checking.
    if ( timerHandle != null && timerHandle.equals( timer.getHandle() ) )
    // do sth.
    else
    //do another thing.
    The result is always drop in else block.
    By doing this is working on WAS7 and JBoss4xx (getting to if block). I was wondering if WebLogic doesn't implements equals and hashCode method then is there another way to check that the retrieved TimerHandle is the same one as timer.getHandle()?
    I'm thinking of adding some unique ID to see if timehandle is the same one or not? However as I mentioned, It works on WAS and JBoss. Does WebLogic has another way to handle my scenario?
    Any help would be appreciate.
    Thanks in advance,
    Nattachai W.

    As you have suggested, it looks like we don't override the equals() method on either our local or clustered TimerHandle implementations.
    We opened a bug (9558396) so we can address it in a future patchset.
    In the meantime, if you have an Oracle support contract, you could open a service request and ask for a patch for bug 9558396 to be created.
    -steve-

  • Comparing dynamic fields of objects using equals and hashCode methods

    To compare the different objects of the same class with their contents like jobTitleId, classificationId, deptId & classificationId was to be done and do some manipulations later using Set and Map. I was able to do that by simply overriding the equals and hashCode methods of Object class and was able to fetch the information (like in the following Map).
        Map<LocationData, List<LocationData>>
    The following is the class I used (its been shown to you so that it can be referred for my problem statement):
    LocationData class
        package com.astreait.bulkloader;
        public class LocationData {    
            String locId, deptId, jobTitleId, classificationId;
            @Override  
            public boolean equals(Object obj) {        
                LocationData ld = (LocationData)obj;       
                return this.deptId.equals(ld.deptId) && this.jobTitleId.equals(ld.jobTitleId) && this.classificationId.equals(ld.classificationId) &&
        this.locId.equals(ld.locId);   
            @Override  
            public int hashCode() {        
                return deptId.hashCode() + jobTitleId.hashCode() + classificationId.hashCode() +locId.hashCode();  
    Problem:
    I'm already known to which all fields of this object I need to make the comparison.
    i.e I'm bound to use the variables named classificationId, deptId, jobTitleId & locId etc.
    Need:
    I need to customize this logic such that the fields Names (classificationId, deptId, jobTitleId & locId etc) can be pulled dynamically along with their values. So, as far as my understanding I made use of 2 classes (TableClass and ColWithData) such that the List of ColWithData is there in TableClass object.
    I'm thinking what if I override the same two methods `equals() & hashCode();`
    such that the same can be achieved.
        TableClass class #1
        class TableClass{
            List<ColWithData> cwdList;
            @Override
            public boolean equals(Object obj) {
                boolean returnVal = false;
                        // I need to have the logic to be defined such that
                        // all of the dynamic fields can be compared
                return returnVal;
            @Override
            public int hashCode() {
                int returnVal = 0;
                        // I need to have the logic to be defined such that
                        // all of the dynamic fields can be found for their individual hashCodes
                return returnVal;
    ColWithData class #2
        class ColWithData{
            String col; // here the jobTitleId, classificationId, deptId, locId or any other more fields info can come.
            String data; // The corresponding data or value for each jobTitleId, classificationId, deptId, locId or any other more fields.
    Please let me know if I'm proceeding in the right direction or I should make some any other approach. If it is ok to use the current approach then what should be performed in the equals and hashCode methods?
    Finally I need to make the map as: (Its not the concern how I will make, but can be considered as my desired result from this logic)
        Map<TableClass, List<TableClass>> finalMap;

    Hello,
    What is the relation with the Oracle Forms tool ?
    Francois

  • Implementing equals() and hashcode

    Hi,
    I need to implement equals() and hashcode() in a class. I only need to use one class variable in the equals() method; String id.
    I'm having difficulties to understand the examples I've seen - can someone please help me out?
    regards, Puzz

    And I know you said you had a hard time understanding some examples, but I'm not sure which examples you've seen. Here is some recommended reading that I think explains this concept well:
    Sun's Java Tutorial: The equals and hashCode Methods
    Josh Bloch: Effective Java
    JavaWorld: Implementing equals and hashCode
    IBM: Defining hashCode() and equals() effectively and correctly
    JavaPractices: Implementing hashCode
    JavaWorld: override hashcode/equals
    ~

  • How equals and hashCode fail here?

    I have a set of Address objects. The pair of equals and hashCode are generated by Eclipse as the following:
         @Override
         public int hashCode() {
              final int prime = 31;
              int result = super.hashCode();
              result = prime * result + ((city == null) ? 0 : city.hashCode());
              result = prime * result
                        + ((cityCode == null) ? 0 : cityCode.hashCode());
              result = prime * result + ((country == null) ? 0 : country.hashCode());
              result = prime * result + ((entry == null) ? 0 : entry.hashCode());
              result = prime * result + ((number == null) ? 0 : number.hashCode());
              result = prime * result + ((phone == null) ? 0 : phone.hashCode());
              result = prime * result
                        + ((postalCode == null) ? 0 : postalCode.hashCode());
              result = prime * result
                        + ((province == null) ? 0 : province.hashCode());
              result = prime * result + ((street == null) ? 0 : street.hashCode());
              return result;
         /* (non-Javadoc)
          * @see java.lang.Object#equals(java.lang.Object)
         @Override
         public boolean equals(Object obj) {
              if (this == obj)
                   return true;
              if (!super.equals(obj))
                   return false;
              if (getClass() != obj.getClass())
                   return false;
              final AddressEntity other = (AddressEntity) obj;
              if (city == null) {
                   if (other.city != null)
                        return false;
              } else if (!city.equals(other.city))
                   return false;
              if (cityCode == null) {
                   if (other.cityCode != null)
                        return false;
              } else if (!cityCode.equals(other.cityCode))
                   return false;
              if (country == null) {
                   if (other.country != null)
                        return false;
              } else if (!country.equals(other.country))
                   return false;
              if (entry == null) {
                   if (other.entry != null)
                        return false;
              } else if (!entry.equals(other.entry))
                   return false;
              if (number == null) {
                   if (other.number != null)
                        return false;
              } else if (!number.equals(other.number))
                   return false;
              if (phone == null) {
                   if (other.phone != null)
                        return false;
              } else if (!phone.equals(other.phone))
                   return false;
              if (postalCode == null) {
                   if (other.postalCode != null)
                        return false;
              } else if (!postalCode.equals(other.postalCode))
                   return false;
              if (province == null) {
                   if (other.province != null)
                        return false;
              } else if (!province.equals(other.province))
                   return false;
              if (street == null) {
                   if (other.street != null)
                        return false;
              } else if (!street.equals(other.street))
                   return false;
              return true;
         }But, the following code fails on the removing an Address object
              boolean found = false;
              for(Address ae : entry.getAddresses()){
                   if((int)ae.getId() == aId){
              if(!entry.removeAddress(address))
                   logger.error("Fail to remove address with ID: " + address.getId());
                        found = true;
                        break;

    warnerja wrote:
    The removeAddress method is implemented as the following:
              address.setEntry(null);
              return addresses.remove(address);
    So you set the entry property to null (and presumably it wasn't null beforehand), and then invoke remove with that object. Well, since entry is one of the properties included in the criteria for equality, don't you see a problem with that? It can't find an object "equal" to that one, since the only ones it finds don't match ALL of the fields included in the equality criteria anymore, since you just wiped out one of them on the target object to find.
    Here's another thing that looks suspect:
    for(Address ae : entry.getAddresses()){
    if(!entry.removeAddress( address ))
    ...Note the bolded parts. Anything strike you as odd?warnerja spotted my careless code. I shouldn't have address.setEntry(null); before the removal. After one attribute is changed, the object definitely is not the same again.
    BTW, sorry for little bit messy on the sample code. I put together code from various classes to illustrate the problem.

  • Problem in not overriding equals and Hashcode

    I have a very small question. We know that if we do not override the equals and hascode of Object class, we can not use the object in the Hashed collection. Can anybody provide me a concrete example which indicates the problem if we do not override the equals and hascode.

    back to the original question from DebadattaMishra
    I have a very small question. We know that if we do
    not override the equals and hascode of Object class,
    we can not use the object in the Hashed collection.
    Can anybody provide me a concrete example which
    indicates the problem if we do not override the
    equals and hascode.lets extend the example from jverd. Suppose we have a Person and want to store some Score in a HashMapclass Person {
        String name;
        Person(String name) {
            this.name = name;
    class Score {
        int value;
        Score(int value) {
            this.value = value;
    public class PersonTest {
        Map<Person, Score> map = new HashMap<Person, Score>();
        void test() {
            map.put(new Person("John"), new Score(1));
            map.put(new Person("Maria"), new Score(2));
            Score score = searchScore("John");
            System.out.println("Found: " + score);  // Found: null
        Score searchScore(String name) {
            return map.get(new Person(name));
    }if you run test() you will get "Found: null" since the John instance in the HashMap is not the same as used in searchScore. HashMap uses the equals method from Object since we have not overridden it.
    If we add an equals methodclass Person {
        String name;
        Person(String name) {
            this.name = name;
        public boolean equals(Object obj) {
            if(obj instanceof Person) {
                Person p = (Person) obj;
                return name.equals(p.name);
            } else {
                return false;
        // hashcode not overridden
    }we probably will get "Found: null" most if the time. The HashMap uses the hashcode() to create an index for saving the keys, so it mostly will not find the Person.((there is still a very small probability that the correct Person is found))
    It will work fine if we add a hashcode like    public int hashCode() {
            return name.hashCode();
        }I hope this example helped.

  • Class HashSet and hashCode method

    I'm using a HashSet class with elements of class A.
    I define the equals method but when i add a object which is already in the set, this object is duplicate.
    Do i have to define the hashCode method in the class A? If yes, i don't understand why this method is used when adding a object.
    Can you give me a explanation ?

    Yes, you do. The hashCode method is used by HashSet and HashMap to find an object. See the API doc for Object, which explains the relationship between equals and hashCode.

  • Equals and serialized copy

    I have an container that can contains any kinds of other objects and I ignore their nature. The only restriction I put is that those object must be Serializable.
    I have implmeneted a clone() method that make a deep copy with serialization. (See http://developer.java.sun.com/developer/JDCTechTips/2001/tt0410.html )
    Now I want to be able to compare the two objects with equals (and with hashcode). Can I use the serialized value of my object to test the equality? I means return true iff the serialized byte[] contains the same bytes, and computes a hashCode from the serialized byte array?
    Asked otherwise, do we have the garantee of the next assertion:
    equal (this.serialize().serialize() , this.serialize())where serialize and equal are
    class A
        private synchronized byte[] serialize()
            ByteArrayOutputStream baos = new ByteArrayOutputStream(5000);
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(this);
            byte[] result = baos.toByteArray();
            oos.close();
            return result;
        private static equal(byte[] a, byte[] b)
            if (a.length!=b.length) return false;
            for (int i=0;i<a.length;i++) if (a!=b[i]) return false;
    return true;

    Let's forget the problem transient field and asume the
    those fields are not used in the equality comparison.
    I thing I have found a case were it will not work.
    Imagine that the object I serialize is a B-Tree. I
    imagine that even if two objects are equals, it's
    possible that they have two differents tree structure
    and thus a 'naive' serialization will give two
    different byte[].
    Very true. I would not go as far as call it 'naive', rather an efficient serialization would cause this as the tree structure would be traversed differently.
    I'm I wrigth or does it exist a specification that
    impose something like
    a.equals(b) <=> equal(a.serialize(),b.serialize())?No, there is nothing in any specification that imposes that the serialized version of the objects byte-stream is equal if their equals method returns true. I could change the serialVersionUID without changing any other class and your byte-stream would differ, even though the internal structure is retained. Serialization is just to serialize objects and to have a way to read them back into objects again.
    That was why I asked the initial question, which was why you need this functionality? yes, I am still curious
    Regards,
    Peter Norell

Maybe you are looking for

  • How can I delete the reading list in Safari on iPad 2?

    I would like to delete the reading list in Safari on my iPad 2. How do I have to do it?

  • A simple BADI implementation - very urgent

    Hi,   I am new to ABAP. I need a small piece of coding. I am implementing a BADI. There is a table which has 3 fields (MATID, LOCID, STATUS and PLANNING_DATE). For each MATID (material ID), there are many LOCID (Location ID) available. My BADI has to

  • Changing Default Portlets on My Pages for All Users

    Hello, I want to add the Collaboration My Projects Portlet on the default My Pages that comes out of box during a portal install. I did trying going to Default Profiles - Edit Profile Layout - went to the My Pages as the default profile and added My

  • BI Publisher is not opening

    Hi, I'm getting the following error message when trying to open BI Publiser from Oracle BI Answers. Error processing your BI Publisher request. Please contact your administrator to review the log files. Error Details Error Codes: S8VLP8HS. Any thing

  • Windows Support Software via Boot Camp: "keyagent failed to start"

    I am installing Windows 64-bit on a Macbook Pro 13" via Boot Camp. In the Windows support software stage, I get a pop-up msg "Service 'KeyAgent' (KeyAgent) failed to start. Verify that you hae sufficient privileges to start system services. I do have