How to generate strings that share the same hashcode in Java?

前端 未结 6 1297
余生分开走
余生分开走 2020-12-28 10:09

An existing system written in Java uses the hashcode of a string as its routing strategy for load balancing.

Now, I cannot modify the system but ne

6条回答
  •  臣服心动
    2020-12-28 10:42

    Given String X, then String Y = "\u0096\0\0ɪ\0ˬ" + X will share same hashcode with X.

    Explanation:

    1. String.hashcode() returns Integer, and every Integer X in java has property that X = X + 2 * (Integer.MAX_VALUE + 1). Here, Integer.MAX_VALUE = 2 ^ 31 - 1;

    2. So we only need to find String M, which has the property that M's hashcode % (2 * (Integer.MAX_VALUE + 1)) = 0;

    3. I find "\u0096\0\0ɪ\0ˬ" : \u0096 's ascii code is 150,\0 's ascii code is 0, ɪ's ascii code is 618, ˬ's ascii code is 748, so its hashcode is 150 * 31 ^ 5 + 618 * 31 ^ 2 + 748 = 2 ^ 32 = 0;

    It is up to you which string you would like, and I pick this one.

提交回复
热议问题