0
点赞
收藏
分享

微信扫一扫

String重写equals() 和 hashCode() 对比 自定义类重写equals() 和 hashCode()

  1. String重写equals() 和 hashCode()
public boolean equals(Object anObject) {
   if (this == anObject) {
       return true;
   }
   if (anObject instanceof String) {
       String anotherString = (String)anObject;
       int n = value.length;
       if (n == anotherString.value.length) {
           char v1[] = value;
           char v2[] = anotherString.value;
           int i = 0;
           while (n-- != 0) {
               if (v1[i] != v2[i])
                   return false;
               i++;
           }
           return true;
       }
   }
   return false;
}

public int hashCode() {
   int h = hash;
   if (h == 0 && value.length > 0) {
       char val[] = value;

       for (int i = 0; i < value.length; i++) {
           h = 31 * h + val[i];
       }
       hash = h;
   }
   return h;
}

System.out.println("a".hashCode());//97
System.out.println("ab".hashCode());//3105
System.out.println("ab".hashCode() == "ba".hashCode());//false

  1. 自定义类重写equals() 和 hashCode()
import java.util.Objects;

public class Son extends Father{
    private String name;
    private int age;
    private int sex;
    public Son() {
    }

    public Son(String name) {
        this.name = name;
    }

    public Son(int age) {
        super(123);
        this.age = age;
    }

    public Son(String name, int age) {
        this(name);
    }

    public Son(String name, int age, int sex) {
        this(name, age);
        this.sex = sex;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Son son = (Son) o;
        return age == son.age && sex == son.sex && Objects.equals(name, son.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age, sex);
    }
}
public static boolean equals(Object a, Object b) {
 return (a == b) || (a != null && a.equals(b));
}

public static int hash(Object... values) {
  return Arrays.hashCode(values);
}

public static int hashCode(Object a[]) {
   if (a == null)
        return 0;

    int result = 1;

    for (Object element : a)
        result = 31 * result + (element == null ? 0 : element.hashCode());

    return result;
}
举报

相关推荐

0 条评论