0
  1. Can somebody explain, why do we have to implement hashCode() and equals() method everytime we write a new class? Its a good practice to write hashCode() and equals() for a new class?

  2. How Does hashcode() works in hashMap?

  3. Why does TreeSet sort like?

Entries

"102. Hello one o two"
"12. Hello twelve"
"1. Hello One" 

in following manner

"1. Hello One"
"102. Hello one o two"
"12. Hello twelve"

Thanks in Advance.

Sotirios Delimanolis
  • 252,278
  • 54
  • 635
  • 683
user3199285
  • 125
  • 1
  • 9

2 Answers2

0
  1. If not overridden, you inherit the versions of those defined on Object, which work only on object identity rather than on the object's value. It's up to you as the object's designer to say what its "value" is for purposes of equality testing, and to define appropriate .equals() and .hashCode operations which agree with that definition.

  2. https://stackoverflow.com/questions/1894377/understanding-the-workings-of-equals-and-hashcode-in-a-hashmap?rq=1

  3. (As covered in the other answer -- if you're inserting strings, they are compared and sort lexically from left to right.)

keshlam
  • 7,681
  • 1
  • 15
  • 31
0
  1. You don't need to, only if you are using them to compare for equality or place in a Hash*. The standard Object implementation is fine otherwise.

  2. http://en.wikipedia.org/wiki/Hash_table http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html

  3. Because it's an alphabetical string sort and 0 is after . but before 2.

Dawood ibn Kareem
  • 68,796
  • 13
  • 85
  • 101
Tim B
  • 38,707
  • 15
  • 73
  • 123