技术笔记

Java语法基础

why??处于业务需要,我们需要经常需要重写equals,重写了equals如果不重写hashcode会怎样如果两个‘相等对象’其中一个放入hashmap,以另一个来取根本取不到,因为他们hashcode不一样。

Java 语法基础

equals 和 ==

比较

equals和hashcode

为什么同时重写

why??
处于业务需要,我们需要经常需要重写equals,重写了equals如果不重写hashcode会怎样
如果两个‘相等对象’其中一个放入hashmap,以另一个来取根本取不到,因为他们hashcode不一样。

package com.whisper;

/** * Created by whisper on 16/7/13. */
 * Created by whisper on 16/7/13.
 */
class Cat{
    private String color;
    private int age;
    
    public Cat(String color, int age) {
        this.color = color;
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Cat cat = (Cat) o;

        if (age != cat.age) return false;
        return !(color != null ? !color.equals(cat.color) : cat.color != null);

    }

  /*  @Override    public int hashCode() {        int result = color != null ? color.hashCode() : 0;        result = 31 * result + age;        return result;    }*/
    public int hashCode() {
        int result = color != null ? color.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }*/
}

测试:

package com.whisper;

import java.util.*;

public class Main {

    public static void main(String[] args) {
          Cat cat = new Cat("red",20);
          Cat cat1 = new Cat("red",20);
        Map cats = new HashMap<Cat,Integer>();
        cats.put(cat,10);
        System.out.printf(String.valueOf(cats.get(cat1)));
    }
}

如果

http://zhidao.baidu.com/link?url=Q0tKuvjsYQxYYeibgvk9rfaiBW8BMKBRCefIXl_zXXQv0hcG7a7iAOnG_SYmHV7ner9B36j_Kr0k3K1TENYRybrtiaYtkCidvAdMxZkhTy3

怎样重写

http://www.cnblogs.com/honoka/p/4827721.html