问题:创建了一个dog对象,dog对象内容是一样的,使用contains方法结果为false, 而使用字符串,创建对象,使用contains方法结果为true

在这里插入图片描述

package com.cmic.origin.safe;

import com.cmic.origin.safe.entity.Dog;

import java.util.HashSet;

/**
 * @description:
 * @author: zmh
 * @date: 2021-09-15 13:56
 */
public class Name {

    public static void main(String[] args) {


        HashSet<Dog> dogSet = new HashSet<Dog>();
        boolean resultq;
        dogSet.add(new Dog("we have white"));
        System.out.println("We have " + dogSet.size() + " white dogs!");
        resultq = dogSet.contains(new Dog("we have white"));
        System.out.println(resultq);

        HashSet<String> books = new HashSet<String>();
        //添加一个字符串对象
        books.add(new String("Struts2权威指南"));
        books.add(new String("Struts2权威指南"));
        boolean result = books.contains(new String("Struts2权威指南"));
        System.out.println("We have " + books.size() + " books!");
        System.out.println(result);
        //下面输出看到集合只有一个元素
        System.out.println(books);
    }

}

网上查找答案得到:

在这里插入图片描述

所以我重写了hascode()跟equals()方法:

package com.cmic.origin.safe.entity;

/**
 * @description:
 * @author: zmh
 * @date: 2021-09-15 14:19
 */
public class Dog {
    String color;
    public Dog(String s){
        color = s;
    }

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

    }

    @Override
    public boolean equals(Object object) {

        boolean result = false;
        if (object instanceof Dog) {
            Dog that = (Dog) object;
            if (this.hashCode() == that.hashCode()) {
                result = true;
            }
        }
        return result;
    }

}

在这里插入图片描述

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐