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

Similar Messages

  • Hi all .hope all is well ..A quick trim question

    Hi all
    Hope all is well ......
    I have a quick trim question I want to remove part of a string and I am finding it difficult to achieve what I need
    I set the this.setTitle(); with this
    String TitleName = "Epod Order For:    " + dlg.ShortFileName() +"    " + "Read Only";
        dlg.ShortFileName();
        this.setTitle(TitleName);
        setFieldsEditable(false);
    [/code]
    Now I what to use a jbutton to remove the read only part of the string. This is what I have so far
    [code]
      void EditjButton_actionPerformed(ActionEvent e) {
        String trim = this.getTitle();
          int stn;
          if ((stn = trim.lastIndexOf(' ')) != -2)
            trim = trim.substring(stn);
        this.setTitle(trim);
    [/code]
    Please can some one show me or tell me what I need to do. I am at a lose                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

    there's several solutions:
    // 1 :
    //you do it twice because there's a space between "read" and "only"
    int stn;
    if ((stn = trim.lastIndexOf(' ')) != -1){
        trim = trim.substring(0,stn);
    if ((stn = trim.lastIndexOf(' ')) != -1){
          trim = trim.substring(0,stn);
    //2 :
    //if the string to remove is always "Read Only":
    if ((stn = trim.toUpperCase().lastIndexOf("READ ONLY")) != -1){
       trim = trim.substring(0,stn);
    //3: use StringTokenizer:
    StringTokenizer st=new StringTokenizer(trim," ");
        String result="";
        int count=st.countTokens();
        for(int i=0;i<count-2;i++){
          result+=st.nextToken()+" ";
        trim=result.trim();//remove the last spaceyou may find other solutions too...
    perhaps solution 2 is better, because you can put it in a separate method and remove the string you want to...
    somthing like:
    public String removeEnd(String str, String toRemove){
      int n;
      String result=str;
      if ((n = str.toUpperCase().lastIndexOf(toRemove.toUpperCase())) != -1){
       result= str.substring(0,stn);
      return result;
    }i haven't tried this method , but it may work...

  • Quick script question

    Hi all,
    Could anyone advise me if i can add anything within - header('Location: http://www.mysite.co.uk/thankyou.html'); in the script below so as the page
    re- directs back to the main index page after a few seconds ?
    Thankyou for any help.
    <?php
    $to = '[email protected]';
    $subject = 'Feedback form results';
    // prepare the message body
    $message = '' . $_POST['Name'] . "\n";
    $message .= '' . $_POST['E-mail'] . "\n";
    $message .= '' . $_POST['Phone'] . "\n";
    $message .= '' . $_POST['Message'];
    // send the email
    mail($to, $subject, $message, null, '');
    header('Location: http://www.mysite.co.uk/thankyou.html');
    ?>

    andy7719 wrote:
    Mr powers gave me that script so im rather confused at this point in time
    I don't think I "gave" you that script. I might have corrected a problem with it, but I certainly didn't write the original script.
    What you're using is far from perfect, but to suggest it would lay you open to MySQL injection attacks is ludicrous. For you to be prone to MySQL injection, you would need to be entering the data into a MySQL database, not sending it by email.
    There is a malicious attack known as email header injection, which is a serious problem with many PHP email processing scripts. However, to be prone to email header injection, you would need to use the fourth argument of mail() to insert form data into the email headers. Since your fourth argument is null, that danger doesn't exist.
    One thing that might be worth doing is checking that the email address doesn't contain a lot of illegal characters, because that's a common feature of header injection attacks. This is how I would tidy up your script:
    <?php
    $suspect = '/Content-Type:|Bcc:|Cc:/i';
    // send the message only if the E-mail field looks clean
    if (preg_match($suspect, $_POST['E-mail'])) {
      header('Location: http://www.example.com/sorry.html');
      exit;
    } else {
      $to = '[email protected]';
      $subject = 'Feedback form results';
      // prepare the message body
      $message = 'Name: ' . $_POST['Name'] . "\n";
      $message .= 'E-mail: ' . $_POST['E-mail'] . "\n";
      $message .= 'Phone: ' . $_POST['Phone'] . "\n";
      $message .= 'Message: ' . $_POST['Message'];
      // send the email
      mail($to, $subject, $message);
      header('Location: http://www.example.com/thankyou.html');
      exit;
    ?>
    Create a new page called sorry.html, with a message along the lines of "Sorry, there was an error sending your message". Don't put anything about illegal attacks. Just be neutral.
    By the way, when posting questions here, don't use meaningless subject lines, such as "Quick script question". If you're posting here, it's almost certain to be a question about a script. It doesn't matter whether it's quick. Use the subject line to tell people what it's about.

  • Urgent help with quick translation questions

    Hello,
    I am somewhat new to Java. I have a translation to hand in in a few hours (French to English). Argh! I have questions on how I worded some parts of the translation (and also if I understood it right). Could you, great developers, please take a look and see if what I wrote makes sense? I've put *** around the words I wasn't sure about. If it sounds strange or is just plain wrong, please let know. I also separated two terms with a slash, when I was in doubt of which one was the best.
    Many thanks in advance.
    1) Tips- Always ***derive*** the exceptions java.lang.Exception and java.lang.RuntimeException.
    Since these exceptions have an excessively broad meaning, ***the calling layers will not know how to
    distinguish the message sent from the other exceptions that may also be passed to them.***
    2) The use of the finally block does not require a catch block. Therefore, exceptions may be passed back to the
    calling layers, while effectively freeing resources ***attributed*** locally
    3) TIPS- Declare the order for SQL ***statements/elements*** in the constant declaration section (private static final).
    Although this recommendation slightly hinders reading, it can have a significant impact on performance. In fact, since
    the layers of access to data are ***low level access***, their optimization may be readily felt from the user’s
    perspective.
    4) Use “inlining.”
    Inlining is a technique used by the Java compiler. Whenever possible, during compilation, the compiler
    copies the body of a method in place of its call, rather than executing a ***memory jump to the method***.
    In the example below, the "inline" code will run twice as fast as the ***method call***
    5)tips - ***Reset the references to large objects such as arrays to null.***
    Null in Java represents a reference which has not been ***set/established.*** After using a variable with a
    large size, it must be ***reassigned a null value.*** This allows the garbage collector to quickly ***recycle the
    memory allocated*** for the variable
    6) TIPS Limit the indexed access to arrays.
    Access to an array element is costly in terms of performance because it is necessary to invoke a verification
    that ***the index was not exceeded.***
    7) tips- Avoid the use of the “Double-Checked Locking” mechanism.
    This code does not always work in a multi-threaded environment. The run-time behavior ***even depends on
    compilers.*** Thus, use the following ***singleton implementation:***
    8) Presumably, this implementation is less efficient than the previous one, since it seems to perform ***a prior
    initialization (as opposed to an initialization on demand)***. In fact, at runtime, the initialization block of a
    (static) class is called when the keyword MonSingleton appears, whether there is a call to getInstance() or
    not. However, since ***this is a singleton***, any occurrence of the keyword will be immediately followed by a
    call to getInstance(). ***Prior or on demand initializations*** are therefore equivalent.
    If, however, a more complex initialization must take place during the actual call to getInstance, ***a standard
    synchronization mechanism may be implemented, subsequently:***
    9) Use the min and max values defined in the java.lang package classes that encapsulate the
    primitive numeric types.
    To compare an attribute or variable of primitive type integer or real (byte, short, int, long, float or double) to
    ***an extreme value of this type***, use the predefined constants and not the values themselves.
    Vera

    1) Tips- Always ***derive*** the exceptions java.lang.Exception and java.lang.RuntimeException.***inherit from***
    ***the calling layers will not know how to
    distinguish the message sent from the other exceptions that may also be passed to them.***That's OK.
    while effectively freeing resources ***attributed*** locally***allocated*** locally.
    3) TIPS- Declare the order for SQL ***statements/elements*** in the constant declaration section (private static final).***statements***, but go back to the author. There is no such thing as a 'constant declaration section' in Java.
    Although this recommendation slightly hinders reading, it can have a significant impact on performance. In fact, since
    the layers of access to data are ***low level access***, their optimization may be readily felt from the user’s
    perspective.Again refer to the author. This isn't true. It will make hardly any difference to the performance. It is more important from a style perspective.
    4) Use “inlining.”
    Inlining is a technique used by the Java compiler. Whenever possible, during compilation, the compiler
    copies the body of a method in place of its call, rather than executing a ***memory jump to the method***.
    In the example below, the "inline" code will run twice as fast as the ***method call***Refer to the author. This entire paragraph is completely untrue. There is no such thing as 'inlining' in Java, or rather there is no way to obey the instruction given to 'use it'. The compiler will or won't inline of its own accord, nothing you can do about it.
    5)tips - ***Reset the references to large objects such as arrays to null.***Correct, but refer to the author. This is generally considered bad practice, not good.
    Null in Java represents a reference which has not been ***set/established.******Initialized***
    After using a variable with a
    large size, it must be ***reassigned a null value.*** This allows the garbage collector to quickly ***recycle the
    memory allocated*** for the variableAgain refer author. Correct scoping of variables is a much better solution than this.
    ***the index was not exceeded.******the index was not out of range***
    The run-time behavior ***even depends on compilers.***Probably a correct translation but the statement is incorrect. Refer to the author. It does not depend on the compiler. It depends on the version of the JVM specification that is being adhered to by the implementation.
    Thus, use the following ***singleton implementation:***Correct.
    it seems to perform ***a prior initialization (as opposed to an initialization on demand)***.I would change 'prior' to 'automatic pre-'.
    ***this is a singleton***That's OK.
    ***Prior or on demand initializations***Change 'prior' to 'automatic'.
    ***a standard
    synchronization mechanism may be implemented, subsequently:***I think this is nonsense. I would need to see the entire paragraph.
    ***an extreme value of this type******this type's minimum or maximum values***
    I would say your author is more in need of a technical reviewer than a translator at this stage. There are far too serious technical errors in this short sample for comfort. The text isn't publishable as is.

  • Quick NativeWindow questions.

    Hi,
    Two Quick Questions about native window actions (I am using AIR with HTML and JS):
    1. How do you "refer" to minimize button ? - So, when a user clicks minimize, it should do an action defined in javascript.
    2. How to define click event for System tray icon ? - So I can display something when my system tray icon is double-clicked.
    Thanks.

    1. Add an event listener to the window.nativeWindow object, listening for the NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING  or DISPLAY_STATE_CHANGE events.
    2. Add an event listener to your SystemTrayIcon object. You can listen for click, mouseUp or mouseDown events, but doubleClick events are not dispatched by this object.

  • Quick REGEXP_LIKE Question

    Hi everyone,
    Had a very quick question: so I need to retrieve all records that have values in this format "type:123;target_id:456". Note that the numeric value can be 1-6 digits long for either type or target_id.
    Can someone please help me with the regexp_like-ing this?
    Thank you,
    Edited by: vi2167 on May 27, 2009 2:06 PM
    Edited by: vi2167 on May 27, 2009 2:07 PM

    WHERE REGEXP_LIKE(val,'type:\d{1,6};target_id:\d{1,6}')SY.

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

  • Okay quick easy question for all who have successfully uploaded videos

    hi, this is my first post in the Apple forums!
    my quick question:
    I have Quicktime Pro, and am currently exporting a video to the iPod
    but it is taking an unusually long time...
    is this normal (and by long I mean I'm @ 16% and it has been 5 minutes)
    do I just need to be more patient?
    thanks
    ^_^

    don't say that...
    I successfully uploaded videos to my iPod I just was not doing it right
    my question has been answered already so STOP BRINGING IT UP AGAIN
    also, look... many people just got their iPods today and are kinda anxious to see the video capibilities work on them, so If you do not have anything constructive to say (by calling us n00bs), then I suggest you don't say anything at all
    iPod video, Dell modded Windows XP Windows XP > your macs

  • Quick Easy Question About N580GTX-M2D15D5 Bios

    Hey guys!!
    I just have a real quick and easy (i suppose) question!
    I had bios version KH0, and MSI live update found KH1, i downloaded and flashed successfully (DOS window said please restart and press any key to exit) so i did, restarted my computer, and MSI live update utlity and gpu-z and MSI afterburner are all reporting the same bios version i had with the KH0, version 70.10.17.00.01 & date November 09, 2010
    MSI live update is not picking up the update again, so my question is, how do i know if it flashed correctly since the bios date and version remained the same?
    Thanks !

    Quote
    I had bios version KH0, and MSI live update found KH1, i downloaded and flashed successfully (DOS window said please restart and press any key to exit) so i did, restarted my computer, and MSI live update utlity and gpu-z and MSI afterburner are all reporting the same bios version i had with the KH0, version 70.10.17.00.01 & date November 09, 2010
    Quote
    version 70.10.17.00.01
    that's suppose to be, this is the version of the both bioses
    Quote
    & date November 09, 2010
    this is GPU release date, not BIOS date
    Quote
    MSI live update is not picking up the update again, so my question is, how do i know if it flashed correctly
    Get this: https://forum-en.msi.com/index.php?action=dlattach;topic=147603.0;attach=7931
    extract it somewhere, then run info1 , and look for the last line
    Quote
    since the bios date and version remained the same?
    they are not the same, your looking the wrong stuffs

  • TDMS - Quick winning Question....

    We are reviewing TDMS
    We have  one quick question ....
    After 4 years of Journey & age of landscpae, becuase of  SPDD & SPAU was not handled incidentally during "different" patch upgrades. and we assume there is slight inconsistency of " Repository objects"  " Dictionary Objects"...
    We want to acheive  In short
    We want to build a Development System which should be in synch of  " Repository objects"  " Dictionary Objects"... with out any master & application data with TDMS ?
    Can we acheive this or not ...
    TDMS provides all other luxuries, but we could get a straight confirmation as requirement as above.
    Pl Help
    Regards
    PR

    Hi Sriniwas
    If you are asking this question to make a buying decision about TDMS then i would suggest that you get in touch with your SAP customer engagement manager (account manager) and ask him to present you all the capabilities and functionalities of TDMS.
    Current version of TDMS offer multiple options and functionalities which may be useful for you.
    Now regarding the query that you have asked -
    If I understood you correctly you are looking for a functionality using which you want to create a development system which is a copy of your production system such that only repository gets copied over from production to the development system and all the client dependent application data is filtered. In the end you will have your development system which is in perfect sync as far as repository and DDIC is concerned.
    The above can certainly be achieved using the TDMS Shell process within TDMS. TDMS Shell is also used as a process to prepare your receiver system for TDMS data transfer.
    I hope this info helps
    Pankaj.

  • Quick naming question

    Wasnt sure if its a naming issue or not but Ive never ran into the problem and Im not sure how to describe it....so here goes.
    Question: Is there a way to insert a string into the name of a component name and have java see it as the actual component name. (see that question still sounds incorrect)
    What I mean is......
    you have 10 buttons named oneB, twoB, threeB,......tenB
    I need to either change a whole lot of code and make what I want to be simple, very large and complex or, find a way to....
    "one"B.setLocation(whereverNotImportant);
    or
    (someObject.getString( ) ) + B.setLocation(whereverNotImportant);
    It looks really odd to me. If theres a way to do it, it just saved me a lot of annoyance.....if not well, Im gonna need more energy drinks.

    Paul5000 wrote:
    Fair enough. I kept adding features onto the code and it grew into needing something different. Was just hoping there was a quick workaround so I didnt have to go back and recode half of it.When you've got Franken-code, the answer is to recode it.

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

  • Quick Notation Question - Data Rates/Frame Rates/Interlacing

    Finally upgraded to a decent prosumer camera and I'm trying to decipher what the manual is telling me about the many different formats it shoots and and the associated options.  I keep seeing things like "There are two basic shooting modes: 720p and 1080i/p.", which I'm finding confusing.  In my understanding, the "p" in 720p means progressive video and the "i" in 1080i means interlaced.  So what do I make of 1080i/p?
    On top of this, my camera shoots in "native" mode, which drops duplicate frames used in "over 60" formats.  This will give me variations in the notation like:
    720/24pN
    720p Native 60 fps
    1080i/24p
    1080/24PN
    Can someone give me a quick primer about frame rate vs data rate and explain how to read these notations?  I'd appreciate it quite a bit.
    Thanks!

    There are so many cameras, capable of so many different formats that providing a manufacturer and model could be helpful in this discussion.
    Jim's answer is absolutely correct but I'm going to re-state for clarification.
    The i/p designation means you can chose to record as interlaced or progressive for a given resolution.
    It sounds like your camera is designed to "capture" images at 60 frames per second, selecting "native" mode means extra frames are deleted and only the desired frames, based on frame rate setting, are recorded to memory. The advantage of "native" @ 24fps is you save space on your memory card. The advantage of NOT using "native" mode is that all 60 frames per second are recorded, but the file metedata tells playback software to only show the frames needed for the specified frame rate (i.e. 24). Since all 60 frames per second are recorded, you use more memory but you also have the option of retrieving all the those frames, if you so desire, at a later time (i.e. for smoother slo-mo).
    To be honest I don't know what your spec of 1080i/24p means. If that is truly an option then I would guess it means it will record a 24p image but the metedata would indicate the file should playback at 30fps interlaced by adding the proper 3:2 pulldown. This would give you that "film" look in a broadcast compatible format.
    For the most part, you don't want use use any interlaced settings. Very few display devices still in use can properly display interlaced images. Interlacing is only required in some broadcast specifications.
    To answer the second part of your question;
    Frame rates are an indication of how many times the moving image is captured over a given period (per second). Higher frame rates means smoother, more "real life" motion. Data rates can generally be considered an indication of image or audio quality. Higher levels of compression result in lower data rates and (generally) lower quality. If squeezing more hours of footage on fewer memory cards is more important than getting the best image quality, choose a lower data rate. Higher frame rates (more images per second) inherently require a higher data rate to retain the same quality as fewer frames at a lower data rate.

  • Two really quick/dumb questions!

    Hi All,
    I have just bought a new Mac Mini and hooked it up to my Samsung 55 inch TV via HDMI and everything seems do be working great.
    My two dumb questions are:
    1: where on the new OS (I had a Mac 5 years ago and things have changed) is the top "Finder" bar and "disc" icon to save files?
    2: In Safari I do not seem to have a tools bar where I can for example open another tab for a new web page.
    Hope you can help a nubby :-)

    You are running a Mini so it might be that the screen resolution is not exact for your display. I have used a Mini with a conventional display but not HDTV. You might need to go into the settings for the TV to set the screen resolution to accommodate the mini's capabilities. Sorry that  I can't offer more on that score; when I use my Sony Bravia HDTV  it is with the iPad2 and HDMI and I have encountered no issues. Perhaps someone else on the forum has better insight into the Menu Bar problem on the Samsung as the principal display. 

  • How to import mpg files & quick time question

    Hello. I found some previous answers here and followed them, which brings me to now. I bought the QT 6 MPEG-2 PLAYBACK-MAC OS X-INT plug in to allow me to bring mpg files from my sony digital camcorder. I keep getting a message that 'this file is not a movie file'. I don't know how to tell if the MPEG-2 plug in is installed, how can I find out in Quick Time? I have Quick Time Pro.
    What application would be best for me to start editing movies? I have IMovie 6.
    Any help is greatly appreciated.
    thanks

    Hi Trib and welcome to the forums!
    Mpeg2 is the standard compressed final delivery format of a DVD, and is not intended for further editing.
    You need to convert your mpeg2 files to a DV stream that you can edit in iMovie 6.
    For that you need mpegStreamclip:
    http://www.apple.com/downloads/macosx/video/mpegstreamclip.html
    which is free, but you must also have the Apple mpeg2 plugin which you have already installed.

Maybe you are looking for

  • Which is better ASM or file system storage

    Hi all, I need a urgent help from all u gr8 DBAs. I have to give justification to my client that which is better to use between file based option ASM and why?? So can anyone give me some write up in this line?

  • Getting error msg while using SFP tcode to use intaractive ADOBE forms

    Hi All, I wanna make use of Adobe intractive forms in one application. when i use transaction SFP and click on the layout tab i get following error message. Could not start Layout Designer (see long text) Message no. FPUIFB086 Diagnosis The forms des

  • IPConfig shows multiple IPs, NIC config does not?

    I'm not having a problem, but I am curious as to what is going on with my situation. I have 4 servers (Win Server 2008 R2 SP1) with two NICs.  The servers are in 2 Oracle RAC clusters, NOT Windows clusters.  What I've noticed is, if I do an IPCONFIG

  • VBN1 Multiple bundling alternative solution

    Good afternoon sir/ma'am May I know what's the alternative solution or development to solve this problem of the standard 1:1 relationship

  • Is the Waveburner UPC/EAN bug fixed in Logic 9?

    Still on Logic 8 in OSX10.5.8 over here. Anyone seen this? In Waveburner, I go to (Disk->Disk Options->) I enter the UPC code for the CD I'm authoring. I click OK. I go back to it (Disk->Disk Options->) It's not there. Has this been fixed in Logic 9?