String's hashCode()

Dear all,
I have an unique id made of a string. I used hashCode() to covert it to int. However, I don't like an id have the negative value.
How can I convert the hashCode() I got to an unique positive number?
Regards.
Pengyou

pengyou wrote:
I see.
Now I have really a trouble in the context of Ehcache.
The net.sf.ehcache.Ehcache interface defines a method      
"get(java.lang.Object key) Gets an element from the cache".
As it will use the hashcode of Object which I overwrote by string's hashcode,What? Could you rephrase that?
then I might get the wrong element for different objects.
Does it mean Ehcache is wrong the the use of it is wrong?I'm not sure I get your question, and I don't know Ehcache, so it's possible that I get you entirely wrong.
But, there's a common way to use hashCodes and it is used in caching as well, so it might be worth explaining:
As you know the hashCode() of two equal() objects (i.e. two Object a and b for which a.equals(b) and b.equals(a) return true) must always be the same.
As you learned in this thread, the opposite need not be true: two Objects for which a.equals(b) and b.equals(a) return false, might have the same hashCode(). In most (good) hashCode() implementation that occasion is relatively rare, but it can happen.
Now if you use the hashCode() to distribute a Set of objects into separate buckets, then that's fine, as long as the hashCode is not the only criterium that's used for retrieving the object.
That means that if you have found an object with the same hashCode(), then you need to check if it is indeed the correct one by calling equals(). The trick is that you only have to do that equals() call for very few objects, since most objects will have different hashCode()s.

Similar Messages

  • Two objects created at the same time with the same hashcode

    We have this object with the following constructor:
    2010-06-24 00:10:31,260 [LoadBalancerClientSubscriber(3)(pid:24312)] INFO  com.intel.swiss.sws.netstar.application.caching.framework.data
    set.synchronizer.DatasetSynchronizer - Initializing dataset synchronizer for: [/nfs/iil/iec/sws/work/damar/ds_cama/tmp/ds_126631277304794
    /d81], i am com.intel.swiss.sws.netstar.application.caching.framework.dataset.synchronizer.DatasetSynchronizer@2ed3cae0
    2010-06-24 00:10:31,260 [LoadBalancerClientSubscriber(5)(pid:24315)] INFO  com.intel.swiss.sws.netstar.application.caching.framework.data
    set.synchronizer.DatasetSynchronizer - Initializing dataset synchronizer for: [/nfs/iil/iec/sws/work/damar/ds_cama/tmp/ds_126631277304794
    /d31], i am com.intel.swiss.sws.netstar.application.caching.framework.dataset.synchronizer.DatasetSynchronizer@2ed3cae0Note that two objects are created by different threads with exactly the same hash code. Any idea if/how this is possible?

    isocdev_mb wrote:
    The last part definitely suggests already that relying on uniqueness is incorrect. Hash codes are very often equal on distinct objects, viz. new String("java").hashCode == new String("java").hashCode(). Use a class level counter as suggested earlier.For that case we would of course expect the hashCodes to be equal, since the objects are equal. But even in the case of non-equal objects that don't override hashCode, you can still get the same value. Or, for that matter, non-equal objects that do override it. There are 2^32 possible hashCode values. There are 2^64 possible Long values. That means that there are 2^32 Longs that have a hashCode of 1, 2^32 Longs that have a hashCode of 2, etc.
    And for non-equal objects...
    package scratch;
    import java.util.Set;
    import java.util.Map;
    import java.util.HashMap;
    public class HashCodeIsNotUnique {
      public static void main(String[] args) throws Exception {
        Map<Integer, Integer> hashCodeCounts = new HashMap<Integer, Integer>();
        int numObjects = 10000;
        for (int i = 0; i < numObjects; i++) {
          Object obj = new Object();
          int hashCode = obj.hashCode();
          if (!hashCodeCounts.containsKey(hashCode)) {
            hashCodeCounts.put(hashCode, 0);
          hashCodeCounts.put(hashCode, hashCodeCounts.get(hashCode) + 1);
        for (Map.Entry<Integer, Integer> entry : hashCodeCounts.entrySet()) {
          int key = entry.getKey();
          int value = entry.getValue();
          if (value > 1) {
            System.out.println(key + " occurred " + value + " times");
    9578500 occurred 2 times
    14850080 occurred 2 times

  • About hashCode()

    hello, i just want to ask, if a certain string converted
    into a hash code can be retrieve/turn back to it's
    original form?
    ex. String n = "alice"; ---> int value = n.hashCode();
    can "value" return to "n" as (alice)?
    can they provide example code in order to help me solve
    my problem? thanks in advance..

    No.
    A tiny bit of logic will tell you this is impossible. There are 2^32 possible hashcode values. There are far more possible strings. Hashcode is not intended to be unique or reversible.

  • Switch with a string?

    Is it possible to do a switch with a String?
    The following does not seem to work
    String a = "bubble";
    switch(a) {
      case "tricks":
        System.out.println("This trick doesn't seem to work");
        break;
      case "bubble":
        System.out.println("It's gone and burst my bubble");
        break;
    }Any ideas?
    Thanks
    Bubble

    Brannor:
    E.g. switch (testString.hashCode()) {
    case ("case 1".hashCode())...This won't work. You need a constant expressions for the cases, a method like hashCode() won't work there.
    Yogee:
    1. Different Strings are not guaranteed to generate different hashcodes.True, but its such a unlikely event that the strings' hashcodes will be equal that someone would still be able to do this reasonably in some situations. but I wouldn't do this in my code
    2. The algorithm used to generate the hashcode is not guaranteed to be the same on different platforms.There is a String hashcode formula, and its not ambiguous. The method is implemented entirely in java and so it will be the same on different platforms. Object.hashCode() though can be different on different platforms.
    3. The algorithm used to generate the hashcode is not guaranteed to be the same on different
    java versions.We can use that argument against writing anything in the API though, since the language can always change. Has Sun ever indicated that they might want to change the API specs for Strings's hashCode?

  • Hashtable vs Vector

    Hi there,
    I was just wondering if a Hashtable is more efficient than a Vector for holding small amounts of objects.
    The fuctionality that I require allows me to use either but Id like to use the most efficient if I can find out which that would be.
    Thanks,
    Nick

    Fiontan,
    You can't compare two things that are not comparable.My bad, the Comparable interface is a Java 2 construct also. You could still code your own binary search for the Vector however, using the knowledge that it only contains Strings, which you can manually compare.
    Or, if speed really isn't important, then you could use the existing contains (was this in 1.0?) or indexOf method to test if the string exists, and just go with the linear performance. In a list with 5 elements (Each equally likely), that's less than 3 comparisons on average, compared with more than 1 (hash + equals, at minimum) for a hashtable.
    The hashtable is a special structure used to keep
    objects that are unique and accessible through a
    unique hashcode, so the access can be make in O(1).A hashtable is an implementation of both the (mathematical) map and (mathematical) set construct. A map is a function that literally maps a value from one set onto another value from another (or the same) set. If a map simply maps a value onto itself, then that map is just an identity map on a set.
    This differs from a Vector, which is simply an ordered list of values. Such a list can be a backing for larger mathematical constructs (Indeed, a similar ordered list forms part of the backing for a hashtable). Since their purpose overlaps, there may well be cases where either is appropriate. In many such cases, there will be one which is 'obviously' more appropriate, but that's no reason to assume that in all cases it is either 'one or the other'.
    But, if you don't have any key on your objects, and
    you want to add the same object several times, and you
    want to have an sequential ordered access : use a
    Vector (or a similar structure) but not an HashTable.I'd change each of your 'and's to 'or's, since a hashtable will not fulfil any of those requirements - so any one of them will render a hashtable unusable. Note that in a set, an object forms its own key.
    Just to throw a spanner in the works, I suddenly recall that in Java 1.0, String's hashCode method was rather inefficient - it creates a poor hash, and it doesn't store the result of the calculation (Meaning it is recalculated for each call to hashCode). If your strings are large, the Vector may match or out-perform the HashTable!
    -Troy

  • Data corruption in HashMap

    I have implemented a server side cache using a HashMap but occassionally the data in the map seems to get dirty.
    It seems that the key-value mapping goes mad and you get the wrong value for a given key. Any ideas why? coz I have run out of ideas on this one :0)
    Here is the the complete source code.....
    package blotter.cache;
    //This interface defines the methods that must be
    //implemented by all objects that wish to be placed
    //in the cache.
    public interface Cacheable
    public boolean isExpired();
    public Object getIdentifier();
    package blotter.cache;
    import java.util.Date;
    import java.util.Calendar;
    // This ia generic cache object wrapper that implements
    // the Cacheable interface. It uses a time to live strategy
    // to object expiration.
    public class CachedObject implements Cacheable
    private Date dateofExpiration = null;
    private Object longIdentifier = null;
    public Object object = null;
    public CachedObject(){}
    public CachedObject(Object obj, Object id, int minutesToLive){
    this.object = obj;
         this.longIdentifier = id;
         setMinutesToLive(minutesToLive);
    public boolean isExpired(){
    // If minutes to live is zero then the object lives forever
         if (dateofExpiration != null){
         // date of expiration is compared to the current date and time
         if (dateofExpiration.before(new Date())){
         System.out.println("Object expired from the cache! EXPIRE TIME: " + dateofExpiration.toString() + " CURRENT TIME: " + (new java.util.Date()).toString());
              return true;
         else{
         System.out.println("Object has not expired from the cache!");
              return false;
         else // This means it lives forever!
         return false;
         public Object getIdentifier(){
         return longIdentifier;
         public Object getObject(){
         return object;
         public void setObject(Object object){
         this.object=object;
         public void setMinutesToLive(int minutesToLive){
    // minutesToLive of 0 means the object lives on indefinitely.
         if (minutesToLive != 0){
         dateofExpiration = new Date();
              Calendar cal = Calendar.getInstance();
              cal.setTime(dateofExpiration);
              cal.add(cal.MINUTE, minutesToLive);
              dateofExpiration = cal.getTime();
    package blotter.cache;
    import java.util.HashMap;
    import java.util.Collections;
    import java.util.Map;
    import java.util.Set;
    import java.util.Iterator;
    import java.util.Calendar;
    import java.util.Date;
    import java.lang.Integer;
    //import blotter.*;
    // This class Manages the objects that have been placed in the cache.
    public class CacheManager {
    // Create a cache with an initial capacity of 3000
    private static Map cacheHashMap = Collections.synchronizedMap(new HashMap(3000));
    // Time to clean the cache
    private String timeToCleanCache = "21";
    private String nextTimeToCleanCache = "22";
    // The thread will run every 45 mins (45 * 60 * 10000 millisecs) to clean
    // the cache of expired objects.
    private int delay = 45 * 60 * 1000;
    private Housekeeper housekeeper=new Housekeeper(delay);
    class Housekeeper extends Thread {
    int interval;
    Housekeeper(int interval) {
         this.interval = interval;
         public void run() {
         try{
         while(true){
              checkExpiry();
              System.out.println("Completed checking for expired Items in the cache");
              Thread.sleep(this.interval);
              System.out.println("Thread gone to sleep for: " + "[ " + this.interval/1000 + "]" + " seconds");
              } //end of the while loop
              }catch (Exception e){
              System.err.println("Exception caught in thread " + e.getMessage());
    public void end(){}
         private void checkExpiry(){
         Calendar cal = Calendar.getInstance();
    Date date = cal.getTime();
         Integer hourOfDay = new Integer(date.getHours());
         Integer minuteOfDay = new Integer(date.getMinutes());
         String hour = hourOfDay.toString();
         String minute = minuteOfDay.toString();
         // Destroy the cache at 9PM and then 10PM every night and create a new one.
         if (hour.equals(timeToCleanCache) || hour.equals(nextTimeToCleanCache)){
         Integer size = new Integer(cacheHashMap.size());
         System.out.println("There are: " + "[" + size.toString() + "]" + " objects in the cache");
         // destory the cache and garbage collect
         cacheHashMap = null;
         System.gc();
         System.out.println("Destroyed the cache at " + "[" + hour + ":" + minute + "]");
    cacheHashMap = Collections.synchronizedMap(new HashMap(3000));
    System.out.println("Created a new cache at " + "[" + hour + ":" + minute + "]");
    } // end of if
         } // end of checkExpiry() method
    public CacheManager(){
    // Sets the thread's priority to the minimum value.
         housekeeper.setPriority(Thread.NORM_PRIORITY);
         // Starts the thread.
         housekeeper.start();
    public void putCache(Cacheable object){
    // Remember if the HashMap already contains a mapping for the key, the old value
    // will be replaced. This is valid functioning for a cache.
    cacheHashMap.put(object.getIdentifier(), object);
    public Cacheable getCache(Object identifier){
    Cacheable object = (Cacheable)cacheHashMap.get(identifier);
    // The code to create the object would be placed here.
    if (object == null)
    return null;
    if (object.isExpired()){
    cacheHashMap.remove(identifier);
    return null;
    else {
    return object;
    public Map getHash(){
              return this.cacheHashMap;
    public Iterator keys(){
         return cacheHashMap.keySet().iterator();
    } // end of CacheManager

    Looks good to me. This example gets to the heart of the matter. Running this will give you the same hash# for the Strings in the different threads, but different hash#'s for the Objects in the different threads.
    It returned this from my workstation. Note 'String:' and 'Hashable:' are the same, while "Object:' is different.
    C:\Dev>java hashtest
    *** THREAD1
    String: 121201685
    Object: 4152583
    Hashable Object: 3188
    *** THREAD 2
    String: 121201685
    Object: 13288040
    Hashable Object: 3188
    class Contact implements java.io.Serializable
        protected String firstName;
        public String getFirstName() { return firstName; }
        public void setFirstName(String _firstName) {
         firstName = _firstName;
    class HashableContact extends Contact
        public int hashCode() {
         return firstName.hashCode();
    public class hashtest
        public static void main(String[] args)
         new Thread() {
             public void run() {
              System.out.println("*** THREAD1");
              System.out.println("String: " + "Thequickbrownfox".hashCode());
              Contact c = new Contact();
              c.setFirstName("cw");
              System.out.println("Object: " + c.hashCode());
              HashableContact hc = new HashableContact();
              hc.setFirstName("cw");
              System.out.println("Hashable Object: " + hc.hashCode());
         }.start();
         new Thread() {
             public void run() {
              System.out.println("*** THREAD 2");
              System.out.println("String: " + "Thequickbrownfox".hashCode());
              Contact c = new Contact();
              c.setFirstName("cw");
              System.out.println("Object: " + c.hashCode());
              HashableContact hc = new HashableContact();
              hc.setFirstName("cw");
              System.out.println("Hashable Object: " + hc.hashCode());
         }.start();
    }

  • Switch: constant expression required

    Hi,
    i initialize some integer constants with the hash code of some strings. However, i cannot use these constants in "case"s of "switch". How can i deal with this?
    Here's the code:
        public void parseHeader()
            char[] headerChars=header_.toCharArray(); //the array representation of the XML header tag
            StringBuffer sBuffer=new StringBuffer();  //the String
            char c=' ';
            int fieldCode=0;
            for (int i=0; i<headerChars.length; i++)
                c=(char)headerChars;
    if (c=='\n')
    switch(fieldCode)
    case ACCEPT:
    sAccept_=new String(sBuffer);
    break;
    case ACCEPT_CHARSET:
    sAcceptCharset_=new String(sBuffer);
    break;
    case ACCEPT_ENCODING:
    sAcceptEncoding_=new String(sBuffer);
    break;
    case ACCEPT_LANGUAGE:
    sAcceptLanguage_=new String(sBuffer);
    break;
    case AUTHORIZATION:
    sAuthorization_=new String(sBuffer);
    break;
    case CACHE_CONTROL:
    sCacheControl_=new String(sBuffer);
    break;
    case CLIENT_IP:
    sClientIp_=new String(sBuffer);
    break;
    case INT_CONNECTION:
    sConnection_=new String(sBuffer);
    break;
    case CONTENT_LANGUAGE:
    sContentLanguage_=new String(sBuffer);
    break;
    case CONTENT_LOCATION:
    sContentLocation_=new String(sBuffer);
    break;
    case CONTENT_MD5:
    sContentMD5_=new String(sBuffer);
    break;
    case WARNING:
    sWarning_=new String(sBuffer);
    break;
    case X_FORWARDED_FOR:
    sXForwardedFor_=new String(sBuffer);
    break;
    case X_SERIAL_NUMBER:
    sXSerialNumber_=new String(sBuffer);
    break;
    default:
    System.err.println("Header field with hash code: "+fieldCode+" detected");
    else if (c==':')
    fieldCode=new String(sBuffer).hashCode();
    sBuffer=new StringBuffer();
    else
    sBuffer.append(c);
    private static final int ACCEPT= "Accept".hashCode();
    private static final int ACCEPT_CHARSET="Accept-Charset".hashCode();
    private static final int ACCEPT_ENCODING="Accept-Encoding".hashCode();
    private static final int ACCEPT_LANGUAGE="Accept-Language".hashCode();
    private static final int AUTHORIZATION="Authorization".hashCode();
    private static final int CACHE_CONTROL="Cache-Control".hashCode();
    private static final int CLIENT_IP="Client-ip".hashCode();
    private static final int CONNECTION="connection".hashCode();
    private static final int CONTENT_LANGUAGE="Content-Language".hashCode();
    private static final int CONTENT_LOCATION="Content-Location".hashCode();
    private static final int CONTENT_MD5="Content-MD5".hashCode();
    private static final int WARNING="Warning".hashCode();
    private static final int X_FORWARDED_FOR="X-Forwarded-For".hashCode();
    private static final int X_SERIAL_NUMBER="X-Serial-Number".hashCode();
    Message was edited by:
    uig

    the labels in a switch-case statement have to be compile-time constant. Anything that involves calling a method is not.
    you could make an enumerated type
    http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html

  • Unmanaged switch with CDP?

    I am trying to find an unmanaged cisco switch that has cdp.  Technically the switch doesn't have to be unmanaged, but I am looking for a cheep switch with only 5-10 ports that also has cdp.  I can't be sure if the small cisco SD series switches, formerly s***sys, have cdp now or not.

    Brannor:
    E.g. switch (testString.hashCode()) {
    case ("case 1".hashCode())...This won't work. You need a constant expressions for the cases, a method like hashCode() won't work there.
    Yogee:
    1. Different Strings are not guaranteed to generate different hashcodes.True, but its such a unlikely event that the strings' hashcodes will be equal that someone would still be able to do this reasonably in some situations. but I wouldn't do this in my code
    2. The algorithm used to generate the hashcode is not guaranteed to be the same on different platforms.There is a String hashcode formula, and its not ambiguous. The method is implemented entirely in java and so it will be the same on different platforms. Object.hashCode() though can be different on different platforms.
    3. The algorithm used to generate the hashcode is not guaranteed to be the same on different
    java versions.We can use that argument against writing anything in the API though, since the language can always change. Has Sun ever indicated that they might want to change the API specs for Strings's hashCode?

  • A hash function

    Hi,
    I am doing a project in which I hope to build a database on the one of 3 servers and in fact I will build 3 databases totally. When I send keys and datas to server from client, I hope to put them into databases equally, i.e. the amount of data on every server are as equal as possible. Now, I am using the following method:
    In general, key is string and I convert the string to number N;
    m = N % 3;
    if m = 1, put the key and the corresponding data into the database on server 1;
    if m = 2, put the key and the corresponding data into the database on server 2;
    if m = 3, put the key and the corresponding data into the database on server 3;
    When I query the data, I also use m' = N % 3 to decide which server I should go to search my data.
    Right now the problem is that for persons, most of them may use some letters more often than other letters. And thus the amount of the three databases may be not equal. Can any one give another method, a hash function, to solve this problem or give me some ideas about some books or some websites?
    Thanks a lot.

    I think that the following method can is good for the
    evenly distribution,and this is on the webstie of
    http://wwwcsif.cs.ucdavis.edu/~fletcher/classes/110W98/
    ecture_notes/hash.html
    Polynomial addressing:
    If x is a character string of standard length L (a
    very common situation), then form a polynomial using
    the ASCII values of each character. For example:
    x = ABC
    h(x) = 32^2 * 'A' + 32 * 'B' + 'C'
    Points to note:
    The ASCII values of each character are represented by
    the character placed between single quotes
    The factor 32 is used because it represents
    left-shifting by 5 bits
    This is easily computed using Horner's Rule: in this
    example,
    h(x) = (32 * 'A' + 'B') * 32 + 'C'
    This is easily coded as an iterative loop for
    arbitrary length L
    The general formula for strings of length L:
    h(x) = 32^(L-1) * x1 + 32^(L-2) * x2 + ... + xL
    If the polynomial gets too large during computation
    using Horner's rule, then you can mod out by the table
    size after each iteration:
    h = x1;
    for(i = 2; i <= L; i++)
    h = (h * 32 + xi) % Size;
    (going around in circles)
    This is EXACTLY how String's hashcode function is implemented! At least in the JDKs I have (1.3.1 --> 1.4.2). So my question is still: What's wrong with it?
    Apparently nothing!
    Suns implementation in String uses 31 as the 'magic' number which is perhaps better than 32 because instead of being a single shift, 31 acts as a distributed sum of shifts so that each input bit ends up affecting more bits in the hashcode. So, for example, the LSB's value will reflect every input received (instead of possibly just the last). Nice huh? This is especially important if you're going to %3 the value.
    sjasja's suggestion using 33 as the value has a similar effect.
    So to ensure consisteny (as was overlooked by me and suggested by sjasja) cut&paste the code from String.hashcode and use it.

  • Use hashCode() to compare strings instead of equalsIgnoreCase()

    The HashCode method has a contract which says
    " If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. "
    Hence does it not make sense to use hashcode() method to compare two strings instead of using equals() method ? For example instead of using
    String s = "One";
    System.out.println("Strings equal = "+s.equals("Two"));
    we can write
    String s = "One";
    System.out.println("Strings equal = "+(s.hashCode()=="Two".hashCode()));

    Here is just a short list of strings with 3 characters that has the same hashcodes:
    2NX and 2O9 has same hashCode 50556
    3NX and 3O9 has same hashCode 51517
    4NX and 4O9 has same hashCode 52478
    5NX and 5O9 has same hashCode 53439
    6NX and 6O9 has same hashCode 54400
    7NX and 7O9 has same hashCode 55361
    8NX and 8O9 has same hashCode 56322
    9NX and 9O9 has same hashCode 57283
    :NX and :O9 has same hashCode 58244
    ;NX and ;O9 has same hashCode 59205
    <NX and <O9 has same hashCode 60166
    =NX and =O9 has same hashCode 61127
    NX and >O9 has same hashCode 62088?NX and ?O9 has same hashCode 63049
    @NX and @O9 has same hashCode 64010
    ANX and AO9 has same hashCode 64971
    BNX and BO9 has same hashCode 65932
    CNX and CO9 has same hashCode 66893
    DNX and DO9 has same hashCode 67854
    ENX and EO9 has same hashCode 68815
    FNX and FO9 has same hashCode 69776
    GNX and GO9 has same hashCode 70737
    HNX and HO9 has same hashCode 71698
    INX and IO9 has same hashCode 72659
    JNX and JO9 has same hashCode 73620
    KNX and KO9 has same hashCode 74581
    LNX and LO9 has same hashCode 75542
    MNX and MO9 has same hashCode 76503
    NNX and NO9 has same hashCode 77464
    ONX and OO9 has same hashCode 78425
    PNX and PO9 has same hashCode 79386
    QNX and QO9 has same hashCode 80347
    RNX and RO9 has same hashCode 81308
    SNX and SO9 has same hashCode 82269
    TNX and TO9 has same hashCode 83230Kaj

  • How to override hashcode() in String

    I need to override the hashcode() method in java.lang.String with a cyclic shift hash code. how do I do this? String is final so I cannot extend it. I've looked at all the postings regarding the logic of why hashcode() must be overwritten with equals() etc, but I need some thoughts on how to actually override the method.

    public class MyString { // you are right, you can't extends java.lang.String
      private String str; // but you can wrap it
      public MyString(String s) {
        this.str = s;
      public String get() {
        return this.str;
      // ... implement all or most String methods again ...
      // ... then ...
      public int hashcode() {
        return whatEverYouWant; // but make sure it is consistent with equals
      public boolean equals(Object obj) {
        return (MyString)obj.get().equals(this.get());
    }--lichu                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

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

  • Hashcode uniqueness for strings

    Hi,
    Is the hash code returned by String.hashcode() method unique for all Strings?? If it is not unique, up to what length of string the uniqueness can be ensured??
    Your help is greatly appreciated,
    Thanks and Regards,
    k.s.sridhar

    One other point, it is stressed in the docs thatif..
    obj1.hashCode() == obj2.hashCode()
    then
    obj1.equals(obj2) should also be true.Um, no. That point is not stressed in the docs. The
    point
    that is stressed is that if the objects are equals()
    then
    their hashCode()'s must be equal as well. You wrote
    it
    backwards.Silly me, you are quite correct :)
    To be clear, here are the three things to keep in mind
    while
    writing hashCode():
    1. Whenever it is invoked on the same object more than
    once
    during an execution of an application, the hashCode
    de method
    must consistently return the same integer, provided
    ed no
    information used in equals comparisons on the
    he object is
    modified. This integer need not remain consistent
    nt from one
    execution of an application to another execution of
    of the same
    application.
    2. If two objects are equal according to the
    equals(Object) method,
    then calling the hashCode method on each of the two
    wo objects must
    product the same integer result.
    3. It is not required that if two objects are unequal
    according to
    the equals(Object) method, then calling the
    he hashCode method on
    each of the two objects must produce distinct
    ct integer results.
    However, the programmer should be aware that
    at producing distinct
    integer results for unequal objects may improve the
    he performance
    of hash tables.
    The above was taken from Item 8 in the Effective Java
    book. It
    claims to be quoting the Java docs (which it probably
    is).It does, just about.

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

  • Does anybody know a reliable hashCode-function for strings?

    Hello,
    I would like to exchange hashcodes between clients and server, both running at different jre's (even msjvms are running it) - and for the same string they should be identical.
    Javadoc mentions that Object.hashCode() may vary from imlpementation, but I would need an implementation which would be consistent across jvms.
    Does anybody know a reliable function which does compute a integer-hash-value out of string?
    Reliable means that its quite unlikely that two different strings get the same hash-value (although I know this cannot be guaranteed 100%).
    Thanks in advance, lg Clemens

    Even the hashcode() API points out that
    it is just a suggestion that it returns the memory
    address of an object, an implementation that might
    differ from other JVMs. So if you'd rely on that
    behaviour, you'd need to check JVM vendors as well.True, and that is why you shouldn't rely on the fact that Object.hashCode returns the memory address, but I think it's safe to rely on the fact that String.hashCode returns the same hashCode on all platforms (if they are using the same Java version).
    The javadoc for String.hashCode says:
         * Returns a hash code for this string. The hash code for a
         * <code>String</code> object is computed as
         * <blockquote><pre>
         * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
         * </pre></blockquote>
         * using <code>int</code> arithmetic, where <code>s</code> is the
    * <i>i</i>th character of the string, <code>n</code> is the length of
    * the string, and <code>^</code> indicates exponentiation.
    * (The hash value of the empty string is zero.)
    * @return a hash code value for this object.
    So that contract must be fulfilled by all implementations.
    Kaj

Maybe you are looking for

  • Error while installing EP6.0 sp4.

    Hi all   We have installed WAS 6.4 for abap and java on windows 2000 server . while installinng EP6 sp4 we are getting the following error.  Have any body encountered this type of error while installation? is there any patch requred for WAS6.4 and ja

  • Integration of BO InfoView in portal

    Hi, I am trying to integrate the BO InfoView in portal, the following are the steps i have done. 1. Created a system for BOE - connection test are fine. 2. Imported the BusinessObjectsKM.par, created the BO repository. 3. Changed the properties of th

  • Outline Load Utulity

    Hi I am trying to export Account dimension data using outline load utility, But i am getting error" invalid request". I am using the hyperion planning version 11.1.1.3. Please help out in solving this issue. Thx Naren

  • InDesign CS5 stürzt beim Druck ab

    Guten Tag InDesign CS 5, Version 7.0.3 auf Windows 7 Folgendes Phänomen: Ich erstelle ein neues Dokument, schreibe ein Wort in ein Textfeld, speichere und drucke: InDesign stürzt ab. Exportieren in ein pdf geht. öffne ich ein älteres InDesign-Dokumen

  • HT201304 Will not allow me to buy inapp things there are no restrictions on

    What can I do so I can buy inapp things