Hashcode() question ???

hi again,
i understand that i need to overide the hashCode() methode for a class X if i plan to put it in a hashtable, my question now is how can i generate an unique ID for each instance of X
thanks again for your answer

why? I can see no reason to override hashcode if your
object can't provide a more unique hash number then
the default implementation.Well, the point sort of is, if you have overridden equals, then you have a better implementation. The default implementation of hashcode uses a function based mainly off memory reference, so, if you've overridden equals to key off, say a certain field (like the value of an employees' salary), it would be expected that your hashcode impelmentation also key off of that field. Other wise you could have a situation where:
Employee one = new Employee(300);
Employee two = new Employee(300);
//true
one.equals(two);
//potentially false
one.hashcode() == two.hashcode();since equals keys off of the salary field, while hashcode still keys off of the default implementation (memory reference).

Similar Messages

  • Again hashcode() question ?

    thanks for your several answers,
    but i want a clear and definitive answer for this assertion ?
    i want to use instance of ObjectX in a HashTable.
    if i overide the equals() methode for objectX, have i to do the same for hashCode(), and if yes how can i generate an integer hascode for each distinct object X.
    class ObjectX {
    private int x;
    private int y;
    public boolean equals(ObjectX ox) {
    return (this.x == ox.x);
    public int hasCode() {
    .....how to generate an integer hashCode
    }

    There is no clear and definitive answer for your question. The only answer is that the hashcode calculation should involve the same variables that are involved in the equals calculation. In some way.
    So in your example, two ObjectXes are "equal" if and only if their x variables are equal. So their hashCode() method should return the same value for all ObjectXes that have the same value of x. The easiest way to do this ispublic int hashCode() {
      return x;
    }You can see (if you look at it for a bit) that if two ObjectXes are equal, then their x variables are equal, and hence their hashCode() methods return the same value (namely x). Clearly other methods would work just as well -- for example you could return 2x, or x squared.
    Now if the equals() method compared both the x and y variables, then your hashCode() method should return some function involving both x and y. As setmuss said, x^y would do. So would x+y and x-y.
    As I said, there's no definitive answer for this.

  • Quick hashCode question

    Hi,
    ive read a few previous posts about this and am still not 100% on this. From what i understand, hashCode is worked out using the memory address unless an equals() method is implemented in which case it uses this.
    Is this right or wrong?
    Thanks
    Chris

    Read the API documentation of java.lang.Object.hashCode(). It states three conditions:
    1. the same object must return the same value for hashCode() if it is called multiple times (during the execution of the Java application)
    2. if two objects are equal according to the equals() method, a call to hashCode() of both objects must return the same value
    3. it is not required that if two objects are unequal, they have different values for hashCode().
    Furthermore:
    "As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)"
    Jesper

  • What are the most common questions in the forums?

    I have my own ideas about what are the questions we see asked over and over and over again in here. Everyone post your ideas here so we can compile a FAQ and maybe post it somewhere (Virum, your new site? :) )

    Please do my homework/coursework/think for me
    This has to be by far the most common type of question asked on the forums.
    Classpath questions
    HashCode questions
    Pointer vs Reference Debate (totally spurious but people spew 100's of pages arguing about something that is perfectly obvious)
    A very good Thread that is probably 1000's of entries long by now is the
    "How to get your questions answered promptly" one (or however this is called). A recap of that published somewhere would be of tremendous value, especially if it was presented as a page you had to go through before landing in the forums to post your latest "Java Challenge" aka "do my coursework" on the boards.

  • SCJP 5.0 A question about hashcode() and equals()

    Here's an exercise from a book.
    Given:
    class SortOf {
    String name;
    int bal;
    String code;
    short rate;
    public int hashCode() {
    return (code.length()*bal);
    public boolean equals(Object o) {
    //insert code here
    Which of the following will fulfill the equals() and hashCode() contracts for this
    class? (Choose all that apply)
    A return ((SortOf)o).bal == this.bal;
    B return ((SortOf)o).code.length() == this.code.length();
    C return ((SortOf)o).code.length()*((SortOf)o).bal == this.code.length()*this.bal;
    D return ((SortOf)o).code.length()*((SortOf)o).bal*((SortOf)o).rate ==
    this.code.length()*this.bal*this.rate;
    C is a correct answer but D is also a correct answer according to the book writer,
    and I don't understand why.
    Normally, the rule is that if two objects are equals (according to the equals
    method)) then they must return the same hashcode. If we have two objects A and B;
    and A.bal == 2, A.code.length()==3, A.rate == 4 and B.bal == 4, B.code.length() ==
    3 and B.rate == 2. A and B are equals according with the D answer but they do not
    return the same hashcode.
    May someone help me make it clear?

    Generally ,the instance members decides the equals( ) & hashCode( ) contract . Here the code.length , bal fields are generating the hashCode.
    So it is appropriate to override the equals( ) method in such a way that , thonly those two fields wil decid the equality of the objects .
    Thanks,
    laksh.

  • A question about String.hashCode()

    Why the implementation of hashCode() for String class using 31 as a base?

    Why the implementation of hashCode() for String class
    using 31 as a base?I think it's a magic number. It has been found to produce a reasonably even distribution over the int range.

  • 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

  • Question on hashCode

    So from what I understand, a hashcode specifies an unique integer based on the object's memory address (correct me if I'm wrong).
    So can two objects have the same hashcode?

    Not exactly.
    Object.hashCode() returns a value based on System.identityHashCode(). That may or may not be based on the memory location of the object, but that's implementation dependent. The only guaranteed thing is that an object will have the same idenityHashCode() during its entire lifetime. It's not even guaranteed to be unique (even though it usually is).
    Read the API documentation of Object.hashCode here: http://java.sun.com/javase/6/docs/api/java/lang/Object.html#hashCode()
    It tells you the exact contract of hashCode() (important note: whenever you implement hashCode(), you must implement equals() as well and the other way around).
    The hashCode() method of other classes can (and often does) return different values, based on the values stored in the object. They need not be unique (indeed, if for two objects a and b a.equals(b) returns true, then the hashCode() values of a and b need to be the same).

  • Noob Question: Problem with Persistence in First Entity Bean

    Hey folks,
    I have started with EJB3 just recently. After reading several books on the topic I finally started programming myself. I wanted to develop a little application for getting a feeling of the technology. So what I did is to create a AppClient, which calls a Stateless Session Bean. This Stateless Bean then adds an Entity to the Database. For doing this I use Netbeans 6.5 and the integrated glassfish. The problem I am facing is, that the mapping somehow doesnt work, but I have no clue why it doesn't work. I just get an EJBException.
    I would be very thankfull if you guys could help me out of this. And don't forget this is my first ejb project - i might need a very detailed answer ... I know - noobs can be a real ....
    So here is the code of the application. I have a few methods to do some extra work there, you can ignore them, there are of no use at the moment. All that is really implemented is testConnection() and testAddCompany(). The testconnection() Methode works pretty fine, but when it comes to the testAddCompany I get into problems.
    Edit:As I found out just now, there is the possibility of Netbeans to add a Facade pattern to an Entity bean. If I use this, everythings fine and it works out to be perfect, however I am still curious, why the approach without the given classes by netbeans it doesn't work.
    public class Main {
        private EntryRemote entryPoint = null;
        public static void main(String[] args) throws NamingException {
            Main main = new Main();
            main.runApplication();
        private void runApplication()throws NamingException{
            this.getContext();
            this.testConnection();
            this.testAddCompany();
            this.testAddShipmentAddress(1);
            this.testAddBillingAddress(1);
            this.testAddEmployee(1);
            this.addBankAccount(1);
        private void getContext() throws NamingException{
            InitialContext ctx = new InitialContext();
            this.entryPoint = (EntryRemote) ctx.lookup("Entry#ejb.EntryRemote");
        private void testConnection()
            System.err.println("Can Bean Entry be reached: " + entryPoint.isAlive());
        private void testAddCompany(){
            Company company = new Company();
            company.setName("JavaFreaks");
            entryPoint.addCompany(company);
            System.err.println("JavaFreaks has been placed in the db");
        }Here is the Stateless Session Bean. I added the PersistenceContext, and its also mapped in the persistence.xml file, however here the trouble starts.
    import javax.ejb.Stateless;
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    @Stateless(mappedName="Entry")
    public class EntryBean implements EntryRemote {
        @PersistenceContext(unitName="PersistenceUnit") private EntityManager manager;
        public boolean isAlive() {
            return true;
        public boolean addCompany(Company company) {
            manager.persist(company);
            return true;
        public boolean addShipmentAddress(long companyId) {
            return false;
        public boolean addBillingAddress(long companyId) {
            return false;
        public boolean addEmployee(long companyId) {
            return false;
        public boolean addBankAccount(long companyId) {
            return false;
    }That you guys and gals will have a complete overview of whats really going on, here is the Entity as well.
    package ejb;
    import java.io.Serializable;
    import javax.persistence.*;
    @Entity
    @Table(name="COMPANY")
    public class Company implements Serializable {
        private static final long serialVersionUID = 1L;
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
        @Column(name="COMPANY_NAME")
        private String name;
        public Long getId() {
            return id;
        public void setId(Long id) {
            this.id = id;
       public String getName() {
            return name;
        public void setName(String name) {
            this.name = name;
            System.err.println("SUCCESS:  CompanyName SET");
        @Override
        public int hashCode() {
            int hash = 0;
            hash += (id != null ? id.hashCode() : 0);
            return hash;
        @Override
        public boolean equals(Object object) {
            // TODO: Warning - this method won't work in the case the id fields are not set
            if (!(object instanceof Company)) {
                return false;
            Company other = (Company) object;
            if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
                return false;
            return true;
        @Override
        public String toString() {
            return "ejb.Company[id=" + id + "]";
    }And the persistence.xml file
    <?xml version="1.0" encoding="UTF-8"?>
    <persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
      <persistence-unit name="PersistenceUnit" transaction-type="JTA">
        <provider>oracle.toplink.essentials.PersistenceProvider</provider>
        <jta-data-source>jdbc/sample</jta-data-source>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <properties>
          <property name="toplink.ddl-generation" value="create-tables"/>
        </properties>
      </persistence-unit>
    </persistence>And this is the error message
    08.06.2009 10:30:46 com.sun.enterprise.appclient.MainWithModuleSupport <init>
    WARNUNG: ACC003: Ausnahmefehler bei Anwendung.
    javax.ejb.EJBException: nested exception is: java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
            java.rmi.RemoteException: Transaction aborted; nested exception is: javax.transaction.RollbackException: Transaktion für Zurücksetzung markiert.; nested exception is:
            javax.transaction.RollbackException: Transaktion für Zurücksetzung markiert.
    java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
            java.rmi.RemoteException: Transaction aborted; nested exception is: javax.transaction.RollbackException: Transaktion für Zurücksetzung markiert.; nested exception is:
            javax.transaction.RollbackException: Transaktion für Zurücksetzung markiert.
            at com.sun.corba.ee.impl.javax.rmi.CORBA.Util.mapSystemException(Util.java:243)
            at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.privateInvoke(StubInvocationHandlerImpl.java:205)
            at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.invoke(StubInvocationHandlerImpl.java:152)
            at com.sun.corba.ee.impl.presentation.rmi.bcel.BCELStubBase.invoke(BCELStubBase.java:225)
            at ejb.__EntryRemote_Remote_DynamicStub.addCompany(ejb/__EntryRemote_Remote_DynamicStub.java)I spend half the night figuring out whats wrong, however I couldnt find any solution.
    If you have any idea pls let me know
    Best regards and happy coding
    Taggert
    Edited by: Taggert_77 on Jun 8, 2009 2:27 PM

    Well I don't understand this. If Netbeans created a Stateless Session Bean as a facade then it works -and it is implemented as a CMP, not as a BMP as you suggested.
    I defenitely will try you suggestion, just for curiosity and to learn the technology, however I dont have see why BMP will work and CMP won't.
    I also don't see why a stateless bean can not be a CMP. As far as I read it should not matter. Also on the link you sent me, I can't see anything related to that.
    Maybe you can help me answering these questions.
    I hope the above lines don't sound harsh. I really appreciate your input.
    Best regards
    Taggert

  • Please help me in understanding hashcode()

    I have some doubt with hashcode(), please help me in understanding.
    As it is always advised that whenever you override equals() method, override even hashcode(). As equals() returns the equality of two objects i.e it returns whether two objects are equal or not. The hashcode(), returns int value, i.e if two objects are equal than both hashcode will be same.
    Now my question is:
    1. When equals() method is comparing 2 objects and returning whethere both are equal or not. Then why we need this hashcode().
    2. When this hashcode(), is going to be call?
    Please tell me Whatever I understood is right or not....

    rajalakshmi wrote:
    2. When this hashcode(), is going to be call?
    equals() method will implicitly call hashCode() method to compare objects.No it won't. Where did you get that?
    Here is the actual code to Strings equals method
        public boolean equals(Object anObject) {
         if (this == anObject) {
             return true;
         if (anObject instanceof String) {
             String anotherString = (String)anObject;
             int n = count;
             if (n == anotherString.count) {
              char v1[] = value;
              char v2[] = anotherString.value;
              int i = offset;
              int j = anotherString.offset;
              while (n-- != 0) {
                  if (v1[i++] != v2[j++])
                   return false;
              return true;
         return false;
        }Now, where is hashCode called there?

  • Use of hashCode and equals method in java(Object class)

    What is the use of hashCode and in which scenario it can be used?similarly use of equals method in a class when it overides form Object class. i.e i have seen many scenario the above said method is overridden into the class.so why and in which scenario it has to override?Please help me.

    You could find that out easily with google, that is a standard junior developer interview question.

  • 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.

  • Runexec( ) & Inherited hashCode

    Question:
    Can Runexec( ) be used to start a .exe. or .bat file from
    within a Java program?
    Also,
    Does the Exception class inherit hashcode from the Throwable class.?
    May we contact you?: yes

    If Throwable overrides hashCode, then yes. More likely, Exception inherits it from Object (although one could still argue that the answer is yes).

  • Questions on oracle forms?!?

    Hi, all.
    I need some help for oracle forms 10g.
    I have some very important questions, pls help.
    1) If i have VBean and say this.getCientProperty(Object o). Is this method returning me the value of property specified in the properties palete in oracle forms builder i.e. if i write this.getClientProperty("Name") -> it returns the name of the bean(is it valid for other components like VTextField for example)?
    2)Could i call methods from the server on the client and how? I read that server method could be wrapped in pl/sql procedure(could you give mi simple example)?
    3)As i understand the only way, that one form can communicate with one bean is with getProperty and setProperty methods, is it?
    Thanks in advance.
    Best regards.

    Hi Francois. First i want to thank you, because you are helping me.
    First to say using ugly tags is not a problem, because this xml is only in the memory(it will be nice to be with good tag names but not mandatory).
    Here is what "sign" process means:
    This process is executed on the client not on the server. So after the xml document is generated it must be signed i.e. with java crypto api and bouncy castle api i create signature from this xml(with algorithms from the api) this signature is like hashcode(String). This string must be passed on the server and there with other algorithms to be verified.
    Imagine you have to sign some bank check(represented as web form for example or electronic file) and send it to some person through internet. How could the bank know that this check is signed from you? So i am working to do this possible to sign electronically documents and data. That is the idea. And i created this as a framework like a lib that only needs to be added and used. But our client wants to do the same for oracle forms applications. Unfortunatly i am not oracle forms developer but no body ask me.
    I read the how to debug guide but i have some problems and cant debug. I am using vista 64, i don't know if this may be a problem. My College managed to run debug with your guide but i am not. When i hit debug debug_pjc.html every thing is ok. The form is shown but the debuger is not started.
    Here is the exception:
    D:\DevSuiteHome\jdk\bin\javaw.exe -ojvm -XXdebug,quiet,port49717 -Xbootclasspath/a:D:\DevSuiteHome\jdev\mywork\WebFormSignerBean\WebFormSignerBean\classes;D:\DevSuiteHome\forms\java\frmall.jar sun.applet.AppletViewer file:/D:/DevSuiteHome/forms/java/debug_pjc.html
    Debugger connected to local process.
    proxyHost=null
    proxyPort=0
    connectMode=HTTP, native.
    Forms Applet version is : 10.1.2.0
    java.lang.ClassNotFoundException: com/digisign/WebFormSignerBean
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Class.java:141)
         at oracle.forms.handler.UICommon.instantiate(Unknown Source)
         at oracle.forms.handler.UICommon.onCreate(Unknown Source)
         at oracle.forms.handler.JavaContainer.onCreate(Unknown Source)
         at oracle.forms.engine.Runform.onCreateHandler(Unknown Source)
         at oracle.forms.engine.Runform.processMessage(Unknown Source)
         at oracle.forms.engine.Runform.processSet(Unknown Source)
         at oracle.forms.engine.Runform.onMessageReal(Unknown Source)
         at oracle.forms.engine.Runform.onMessage(Unknown Source)
         at oracle.forms.engine.Runform.sendInitialMessage(Unknown Source)
         at oracle.forms.engine.Runform.startRunform(Unknown Source)
         at oracle.forms.engine.Main.createRunform(Unknown Source)
         at oracle.forms.engine.Main.start(Unknown Source)
         at sun.applet.AppletPanel.run(AppletPanel.java:377)
         at java.lang.Thread.run(Thread.java:534)

  • Hibernate Interview questions

    where can i find technical frequently asked interview questions on hibernate. i am new to hibernate and i want to learn about hibernate
    can anyone please help me

    The purpose of Hibernate is to relieve the developer from a significant amount of common data persistence-related programming tasks. Hibernate adapts to the developer's development process, whether starting from scratch or from a legacy database.
    Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities and can significantly reduce development time otherwise spent with manual data handling in SQL and JDBC. Hibernate generates the SQL calls and relieves the developer from manual result set handling and object conversion, keeping the application portable to all SQL databases.
    Hibernate provides transparent persistence for "Plain Old Java Objects"; the only strict requirement for a persistent class is a no-argument constructor, not compulsorily public. (Proper behavior in some applications also requires special attention to the equals() and hashCode() methods.[1])
    Hibernate is typically used both in standalone Java applications and in Java EE applications using servlets or EJB session beans.

Maybe you are looking for