How to implement hashCode and equals method

前端 未结 6 840
无人共我
无人共我 2020-12-01 12:08

How should I implement hashCode() and equals() for the following class in Java?

class Emp 
{
  int empid ; // unique across all the         


        
6条回答
  •  没有蜡笔的小新
    2020-12-01 13:01

    Guava has helper methods for creating them. You tell it which fields to take in consideration and it will handle nulls for you and do the prime number calculation for hashcode.

    IDEs can also generate them based on the fields you choose.

    The advantage of delegating it to a tool like that is you get a standard solution and will worry less about bugs and maintenance of varied implementations spread all over your project.

    Here's an example of using Guava and generated by an IntelliJ plugin: https://plugins.jetbrains.com/plugin/7244?pr=

提交回复
热议问题