HashCode method execution

Dear Members :
I have custom hashCode method in conjunction with overriden equals method, in my program and have following doubts/observations :
[1] In order to verify whether the hashCode method is executed, I put a println statement within method, but this doesn't output when the program is run.
[2] The program is a simple equality testing of two dates and doesn't make use of any map. I want to know when and who gives (implicit ?) call to this hashCode method, when equals method is overriden, I mean the program flow.
Since SUN suggests to override hashCode, whenever equals method is overriden, and my program is not making use of map, how and when the hashCode method gets called and if so why my test print is not executed ?
Thanks in advance.
Atanu

uj_ wrote:
jverd wrote:
uj_ wrote:
One way to graciously avoid the contract is to override hashCode and let it throw an exception (or assertion) stating "hashCode not implemented. This class is not intended for use in hash-based collections" or something.What would be the advantage of doing that over just taking the 5 minutes needed to implement it properly?Who are you to stipulate other people's design needs? Just because something takes just 5 minutes doesn't mean it's the right thing to do.
You may want a class to have an equals relation based on content but you still may not want the class to be in a hash-based collection. The most compelling reason may be that it's not immutable.
The equals/hashCode contract is mostly a Sun promise regarding "standard" classes. Everybody else design their classes the way they see fit.Calm down UJ. I have as much right to offer my opinion as you have to offer yours. I just asked a simple question.
The requirement that a class not be used in a hash-based collection would be silly. It's up to the user of the class how to store instances. If the fields that go into determining hashCode are mutable, then that should be a documentation issue. There are good reasons to keep hashCode and equals in sync. The only reason not to do so would be the time it takes to write the code. Since that time is trivial for any well-designed class, it's an extremely weak reason.

Similar Messages

  • HashCode() method implementation in KVM

    hi, I've got a problem with the KVM implementation of Object.
    More specifically I verified that Class Objects change their hash codes during a run session of the same VM which seems to be a violation of the rule
    Whenever it is invoked on the same object more than once during
    an execution of a Java application, the hashCode method
    must consistently return the same integer, provided no information
    used in equals comparisons on the object is modified.
    written in the Object class doc
    Suppose I define a class named MyClass. At different times during the execution of my application I may end up writing the following code.
    Object obj1 = new MyClass().getClass();
    System.out.println(obj1.hashCode());
    // Sometime elapses
    Object obj2 = new MyClass().getClass();
    System.out.println(obj2.hashCode());
    System.out.println(obj1 == obj2);What I see in the print out is that the two hashcodes are sometime different while the two objects references exactly point to the same Object consistently returning true as it should be.
    Any hint for this misbehaviour?

    Hey Hi,
        This method determines which entries are offered for selection in the
        dropdown list box for the salary statement. Entries can include, for
        example:
        o   All Salary Statements
        o   3 Salary Statements
        o   6 Salary Statements
        For each entry available for selection, you must specify the sequence
        number of the oldest salary statement displayed in the hit list for
        selection.
        As before, you define the standard selection for this selection list.
    The following export parameters are available:
    Parameter      -      Description
    EX_MESSAGE -          Message
    EX_VALUE_SET_EXT-     ESS: Enhanced ValueSet Structure
    EX_DEFAULT_ENTRY -    Default entry in dropdown list
    INCLUDE HRXSS_SER_VALUE_SET (ESS: Extended Value-Set Structure )
    is nothing but the structurr which has following componants or you can say fields
    VSKEY
    VSVALUE
    SEQNR
    During the RUN times this fields can hold the value and export it to the portal as the Bussiness logic.

  • BI Transport Req Error 8 - Error in Import and Method Execution

    Hi All,
    I have collected the Update Rule in a Transport Request. The Update Rule has couple of lookup routine(s) for the data and key field.
    When Moved the transport request to Quality the same is ending with error 8.
    Error at the time of Import
    R3TRROUT 3AQ..........was repaired in this system
    Object R3TRROUT 3AQ.......... is in repair status.  Therefore cannot be imported
    Procedure: If you still want to import release the relevant repair and repart the import
    Error message at Method Execution Log
    Object ROUT 3AQ.... has not been imported successfully
    The Object R3TRROUT 3AQ.......... has not yet been imported without error.
    Import Post Processing is not performed for this InfoObject.
    Note : I have tried this couple of times but the error remains same. Checked the Routines in development and quality and they are all same....Could not able to analyse what exactly is the error.
    Please help. I am not able to understand how to go a head.

    Dear Pavan,
    Iu2019m going try to help you regarding your question,
    I have been a similar problem with transformation, the transport request after accept in the system target have given a similar error. I have fixed following the next step:
    u2022     I activating again the source and target, if those source and target was changed it is important to transport before the update rule.
    u2022     When you are sure that you have the same source and target in both systems, furthermore both have been activated, you can move on with the transport request of update rule.
    I hope this suggestion can help you to answer your question,
    Luis

  • Import and Method Execution Error (8)

    Hi,
    I having problem in BI 7. when I transport all objects in one transport number such as
    DOSTransformationDTPDSInfoPackage and transport in QA works fine
    but when I move in PRD no efect in there and get this messages:
    Method Execution with error (8)
    I check transport layer and other setting everying is ok... please advised me what should I do
    Thank in Advance
    Angeline

    Hi,
    Check the correct Error log in STMS_IMPORT and then select your error req and click on Log and expand teh message and see the exact error message and corretc it and re transport it.
    Don't mix all obejcts in single request.
    First Transport the Package then
    1. InfoObejcts.
    2. Cubes, DSO's
    3.DataSources from ECC Dev to ECC Qty
    4. DataSource Replication in BW Qty
    5. InfoSources.
    6.Transformations in between DataSource and InfoSource.
    7.Transformations in between InfoSource and InfoCube/DSO.
    8. DTP's & InfoPackages.
    9. Multiproviders/InfoSets.
    10. Reports.
    Thanks
    Reddy

  • How to stop processRequest method execution second time in CO

    Hi all,
    I have a Requirment like to stop ProcessRequest method execution In my controler when i click the button on my page
    Regards,
    Shiva

    Hi Shiva,
    You can make use of session parameters..
    When you click on a button ?? why will the page go to PR method ??
    By default it goes in PFR method.
    Anyways if you are redirecting it to the same page : u can make use of below methods for the same to control the execution of methods in PR.
    While coming back to PR method : check the parameter value.. & make sure that..no methods are executed in it.
    PR Method
    String dieFromUpdate = pageContext.getParameter("DieValue");
    if(dieFromUpdate!=null)
    make use of this condition and execute the statements..
    PF Method
    String Die ='IN PF Method " ;
    pageContext.putParameter("DieValue", Die);
    Regards
    Sridhar

  • Why should we overide hashCode method when we overide equals ?

    Why should we overide hashCode method when we overide equals ?

    java.lang.Swapnil wrote:
    Why should we overide hashCode method when we overide equals ?For the purpose of hashing, you need to override both hashcode and equal method. It is because different objects(in most cases) have different hashcode.
    Edited by: Hunky322 on 28.?ub.2009 16:21

  • 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

  • HashCode method

    How to write overridden hashcode method? Is there any particular rule for it?

    Folks,
    It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables. My two bobs worth is... I'm a simple kind of idiot... I struggle with all the double negatives in Object.hashCode API. So here's my rewrite.
    The equals and hashCode methods share a special relationship.
    The general contract is:
    1. If two objects are equals they must have the same hashCode.
    2. BUT, If two objects have the same hashCode they don't necessarily have to be equals, but this is called "a hashCode clash", which ain't good. A poor hashCode implementation (one which produces a high proportion of "clashes") dramatically slows-down hashMap lookups. In hash-code-land: More distincter is more betterer.
    3. Both equals and hashCode must be consistent over time. The hashCode must remain unchanged unless an attribute effecting equals has changed... at which time the hashCode proabably should change (but see rule 2).
    The rules of thumb for developers are:
    1. The equals and the hashCode methods should examine the same attributes of the object.
    2. So... If you override hashCode you almost certainly need to override equals to fulfill the above contract.
    2. And vice versa: If you override equals you probably need to override hashCode to fulfill the above contract.
    And what the API should say but doesn't is that hashCode only affects Hash* collections (those which begin with the word "Hash") such as HashTable, and HashMap. If you're not using Hash* collections (and are positive that your objects will never be stored in a Hash* collection) then you can get away with totally ignoring hashCode and all of it's innate complexities; with the Caveat Emptor that surety is inversely proportional to the magnitude of the universe of discourse... so you're better off just doing it, coz it's easier than evaluating the consequences of NOT doing it.
    Just my two bobs worth.
    Cheers. Keith.

  • The hashCode() method

    As per the Java API documentation, the hashCode method returns distinct integers for distinct objects. In my code, which used this method for generating unique ids for a large number of objects, I came across a duplication of ids generated (i.e. the int returned by hashCode()).
    Is it possible for two different objects to have same values returned when hashCode method is invoked?
    Can any one please tell me where I can find the implementation code/detailed logic for this Java method?
    JRahul

    With the Identifiable interface.
    As the implementation of getID() should be the same in all of your class where you want to be able to get an unique ID, you could also either defines a abstract class instead of a interface, or create a parent implementing getID() and from which your classes may inherit.
    But in such cases, you cannot extends others class into yours.
    public class UniqueIDTest {
         private final int NUM_INSTANCE = 10;
         private final int NUM_CALL = 5;
         public UniqueIDTest() {
              UniqueID[] uniqueID = new UniqueID[NUM_INSTANCE];
              for (int i = 0; i < NUM_INSTANCE; i++) {
                   uniqueID[i] = new UniqueID();
              for (int i = 0; i < NUM_INSTANCE; i++) {
                   for (int j = 0; j < NUM_CALL; j++) {
                        System.out.println(uniqueID.getID());
         public static void main(String[] args) {
              UniqueIDTest uniqueUDTest = new UniqueIDTest();
    public class UniqueID implements Identifiable {
         public UniqueID() {     }
         public int getID() {
              return IDGenerator.getID();
    public class IDGenerator {
         private static int id = 0;
         private IDGenerator() {} //To avoid instanciation
         public static synchronized int getID() {
              return id++;
    public interface Identifiable {
         public int getID();

  • Role onStop() method execution

    Hello,
    I would like to know if I can always rely on a onStop() method executing? Is there some (realistic) type of hardware, or platform failure that will shutdown or recycle role without previous onStop() method execution? I would like to put part of service recovery
    logic in onStop() method, but that would require for onStop() performing consistently.
    Thanks in advance,
    Nenad Rakic

    Hi Nenad,
    OnStop method is a over-ridable method available in the RoleEntryPoint class which will be called every timewhen your role instance is stopped.
    Whether you can rely on it or not depends upon your requirement as you will get appx 5 minutes of time frame to run your code within OnStop method and after which role instance will be stopped.
    MS Recommends - Code running in the OnStop method
    has 5 minutes to finish when it is called for reasons other than a user-initiated shutdown. After this time elapses, the process is terminated, so you must make sure that code in the OnStop method
    can run quickly or tolerates not running to completion.
    If other code requires time to exit gracefully you should keep the OnStop thread
    busy until execution is complete.
    There might be many reasons which can trigger role instance recycling, e.g. missing referenced assemblies, un-handled exceptions etc.
    Bhushan | http://www.passionatetechie.blogspot.com | http://twitter.com/BhushanGawale

  • Stop the method Execution.

    Hi..
    I have a method call to make a credit card payment.sometimes it takes so much times.If that process takes more than 10 minutes,
    I want to stop that method execution.I have implemented the TimerTask to check the execution time and stop..but I don't have a idea to stop that processing method...
    can anyone give me a suggetion.
    Regards
    Amila

    Hi,
    You may have a look at this thread [http://forums.sun.com/thread.jspa?threadID=5347956&tstart=0]
    I changed the suggested code a little to make it (hopefully) suitable for your use case. Note that the long running task communicates to its invoker via System.out.
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import javax.swing.AbstractAction;
    import javax.swing.Action;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.JToolBar;
    import javax.swing.SwingUtilities;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Document;
    public class TaskDispatcher {
        private static long lengthy = 10000;
        public static void main(String[] args) {
         SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
              new TaskDispatcher().createGUI();
        private JTextPane textPane;
        private JLabel message;
        private Process process;
        private Action kill = new AbstractAction("Kill") {
         private static final long serialVersionUID = 1L;
             this.setEnabled(false);
         @Override
         public void actionPerformed(ActionEvent event) {
             destroy();
        private Action dispatch = new AbstractAction("Dispatch") {
         private static final long serialVersionUID = 1L;
         @Override
         public void actionPerformed(ActionEvent event) {
             dispatch();
        public void createGUI() {
         JFrame frame = new JFrame();
         textPane = new JTextPane();
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         message = new JLabel("Status", JLabel.CENTER);
         JToolBar toolBar = new JToolBar();
         frame.add(toolBar, BorderLayout.PAGE_START);
         frame.add(new JScrollPane(textPane), BorderLayout.CENTER);
         frame.add(message, BorderLayout.PAGE_END);
         toolBar.add(dispatch);
         toolBar.add(kill);
         frame.setSize(400, 400);
         frame.setLocationRelativeTo(null);
         frame.setVisible(true);
        private void appendLine(String line) {
         Document doc = textPane.getDocument();
         try {
             doc.insertString(doc.getLength(), line + "\n", null);
         } catch (BadLocationException e) {
             e.printStackTrace();
        private void destroy() {
         kill.setEnabled(false);
         process.destroy();
         dispatch.setEnabled(true);
        private void dispatch() {
         dispatch.setEnabled(false);
         try {
             textPane.setText("");
             launch();
             kill.setEnabled(true);
         } catch (IOException e) {
             e.printStackTrace();
             dispatch.setEnabled(true);
        private void handleErr(final Process process) {
         new Thread(new Runnable() {
             final BufferedReader errReader;
              errReader = new BufferedReader(new InputStreamReader(process
                   .getErrorStream()));
             @Override
             public void run() {
              try {
                  String line = null;
                  while ((line = errReader.readLine()) != null) {
                   System.err.println("Other JVM: " + line);
              } catch (Throwable t) {
                  t.printStackTrace();
              } finally {
                  try {
                   errReader.close();
                  } catch (IOException e) {
                   e.printStackTrace();
         }).start();
        private void handleOut(final Process process) {
         new Thread(new Runnable() {
             final BufferedReader outReader;
              outReader = new BufferedReader(new InputStreamReader(process
                   .getInputStream()));
             @Override
             public void run() {
              try {
                  String line = null;
                  while ((line = outReader.readLine()) != null) {
                   appendLine(line);
              } catch (Throwable t) {
                  t.printStackTrace();
              } finally {
                  try {
                   outReader.close();
                  } catch (Throwable t) {
                   t.printStackTrace();
         }).start();
        private void launch() throws IOException {
         final String command;
         command = "java -cp \"" + System.getProperty("java.class.path") + "\" "
              + LengthyTask.class.getCanonicalName() + " \"" + lengthy + "\"";
         process = Runtime.getRuntime().exec(command);
         message.setText("Process is running");
         handleOut(process);
         handleErr(process);
         new Thread(new Runnable() {
             @Override
             public void run() {
              try {
                  int rc = process.waitFor();
                  kill.setEnabled(false);
                  if (rc != 0) {
                   appendLine("Exit code " + rc);
                  dispatch.setEnabled(true);
                  message.setText(rc == 0 ? "Completed successfully"
                       : "Problem exit code: " + rc);
              } catch (InterruptedException e) {
                  e.printStackTrace();
         }).start();
    }Piet

  • JPanel repaint() method execution

    Hi,
    I vould like to know if there is a way to catch the end of repaint() method execution.
    Thank you in advance

    This is my scenario ...
    I am using an external tool ,for georeferencied images handling , to generate JPEG images and save them to disk.
    In order to generate an image I overlap n layers provided by this tool ... each time I add a layer I need to repaint the panel and then save the content to disk.
    The problem is that there is a race condition between repaint() and save() method.... in particular ... if I use larger images it takes a long time to repaint the panel and in this while it stores an incomplete image.

  • Overriding hashcode method

    Can u pls tell me friends why should definetly i override the hashcode method if i override equals method of the Object class

    Because the contracts of equals and hashCode are strongly bound to each other.
    For each objects x and y where x.equals(y) returns true x.hashCode() must be equal to y.hashCode().
    If you don't follow this convention you'll get hard-to-find bugs as soon as you use your object as a key in some kind of HashMap/HashTable/...

  • HashCode method return same value for different string?

    Hello. I am finding hashCode method of string return same hashcode for many different string? It seem when string is long we get same value many times? What is solution? I am useing JDK 1.0.2. Thank you.

    Hello. I am finding hashCode method of string return
    same hashcode for many different string? There are about 4 billion possible hashcode values.
    How many possible strings do you think there are?
    Obviously many strings will have the same hashcode.
    What is
    solution?The solution is to not depend on hashcodes being unique.

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

Maybe you are looking for

  • How do I crop a 4x6 aspect portrait photo (using the 4x6 built-in) from a landscape photo?

    I have Lightroom 2, 2.7.  I have read I can just type "x" while in crop mode, but I get a message "Set as rejected" and nothing helpful happens. I have a nice landscape photo with two people... I want to take the left half of the photo and make it a

  • Maßstab in Acrobat X Pro einstellen

    Hallo, ich habe ein PDF, in dem ich mit dem Meßwerkzeug messen will. In den älteren Acrobat-Version konnte ich einen Maßstab einstellen. Bei Acrobat X Pro finde ich weder unter Bearbeiten|Voreinstellungen|Messen (2D) etwas noch unter den Eigenschafte

  • Checkbox without the box

    Hey Forum, I'm trying to create a JCheckbox without it showing the box. The functionality is simple, when a user clicks on the text of the checkbox the check will appear or disappear (but no box should be visible). I'm using this in a JMenu to turn t

  • Unable to run graph on report server

    i am unable to run the graph on report server i have added the XML code from http://www.oracle.com/webapps/online-help/reports/10.1.2/topics/htmlhelp_rwbuild_hs/rwwhthow/howto/additems/add_graph_jsp.htm Adding a graph to a JSP-based Web report but it

  • Unable to Boot MBP after OS X update

    Hey Guys, i tried to update from Tiger to Snow Leopard and midway it said it couldn't be done. I now get the gray apple screen and then it turns off after about 20 seconds. I have tried booting from the Tiger and Leopard install discs but have been u