看了网上关于 equal 与 == 的区别, 感觉很多有些片面, 不仔细, 这里我来说说我对 equal 与 == 的理解
首先要了解基本类型与引用类型
1.int,char,boolean 之类的就是基本类型, 我们只要使用 == 即可判断是否相等, 无法使用 equals
2. 引用类型分为两类, 第一类是重写过 hashcode() 和 equals() 方法的类, 比如 String,Integer, 等, 这些类使用 == 比较的是内存地址, 即不同引用是否指向同一个对象, 是, 则 true.equals 比较则是直接比较对象的内容, 不是判断不同引用是否指向同一个对象, 只要对象里的各种参数完全一致, 就为. true
3. 第二类引用类型, 就是没有重写过 hashcode() 和 equals() 方法的类, 我们看 Object 类下的 equals() 方法
- public boolean equals(Object obj) {
- return (this == obj);
我们知道所有类都是 Object 类的子类, 就是说如果子类不重写 equals() 方法, 那么该类使用 equals() 方法就是使用 Object 下的 equals, 就是不同引用是否指向同一个对象, 是, 则 true. 如果我们希望实现普通类只比较对象的属性, 可以对 hashcode() 和 equals() 进行重写, 下面就是
- class Student {
- private String type;
- private String name;
- private int age;
- Student(String type,String name,int age){
- this.age=age;
- this.type=type;
- this.name=name;
- }
- @Override
- public int hashCode() {
- int B=31; // 31 131 1313 13131 131313 etc..
- int hash=0;
- hash=hash*B+age;
- hash=hash*B+type.toUpperCase().hashCode();
- hash=hash*B+name.toUpperCase().hashCode();
- return hash;
- }
- @Override
- public boolean equals(Object obj) {
- if(this==obj){
- return true;
- }
- if(obj==null){
- return false;
- }
- Student student=(Student) obj;
- return student.hashCode()==this.hashCode();
- }
- }
来源: http://www.bubuko.com/infodetail-3100046.html