【HashSet:重写比较方法示例二】
package com.yjf.esupplier.common.test; import java.util.HashSet; /** * @author shusheng * @description * @Email shusheng@yiji.com * @date 2018/12/14 15:04 */ public class DogDemo { /** * HashSet集合存储自定义对象并遍历,如果对象的成员变量值相同即为同一个对象 * <p> * 注意了: * 你使用的是HashSet集合,这个集合的底层是哈希表结构 * 而哈希表结构底层依赖:hashCode()和equals()方法 * 如果你认为对象的成员变量相同即为同一个对象的话,你就应该重写这两个方法,这两个方法可以自动生成。 */ public static void main(String[] args) { //创建集合 HashSet<Dog> hs = new HashSet<Dog>(); //创建狗对象 Dog d1 = new Dog("秦桧", 25, "红色", "男"); Dog d2 = new Dog("高俅", 22, "黑色", "女"); Dog d3 = new Dog("秦桧", 25, "红色", "男"); Dog d4 = new Dog("秦桧", 20, "红色", "男"); Dog d5 = new Dog("魏宗贤", 28, "败色", "男"); Dog d6 = new Dog("魏宗贤", 28, "败色", "男"); hs.add(d1); hs.add(d2); hs.add(d3); hs.add(d4); hs.add(d5); hs.add(d6); for (Dog d : hs) { System.out.println(d.getName() + "---" + d.getAge() + "---" + d.getColour() + "---" + d.getSex()); } } } class Dog { private String name; private int age; private String sex; private String colour; public Dog() { super(); } public Dog(String name, int age, String sex, String colour) { super(); this.name = name; this.age = age; this.sex = sex; this.colour = colour; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getColour() { return colour; } public void setColour(String colour) { this.colour = colour; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((colour == null) ? 0 : colour.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((sex == null) ? 0 : sex.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Dog other = (Dog) obj; if (age != other.age) { return false; } if (colour == null) { if (other.colour != null) { return false; } } else if (!colour.equals(other.colour)) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } if (sex == null) { if (other.sex != null) { return false; } } else if (!sex.equals(other.sex)) { return false; } return true; } }
终身学习者