Create hash from string and int

前端 未结 6 1783
离开以前
离开以前 2021-02-07 20:14

I remember eclipse and idea have this template to automatically create an object\'s hashCode based on its attributes.

One of the strategies if a number and a string is u

6条回答
  •  攒了一身酷
    2021-02-07 20:50

    Further to your most recent edit, if retrieval speed is more important than storage concerns you could pre-compute and store the hash code when constructing your StringInt class. This is safe as you've marked the String and int fields as final, and also given that String is immutable.

    Also, you could optimise your equals method by checking that the object being compared == this before doing a full comparison. I would also recommend doing the cheaper int-based comparison first before comparing the string fields.

    Another final suggestion: You could change your valueOf(String, int) method to either construct a StringInt or return a previously created instance if one already exists with the same String and int values. This makes construction more expensive but comparisons very cheap as you can compare StringInts using "==" in the knowledge that no two StringInts will ever be created with the same String and int value.

提交回复
热议问题