天天看點

集合架構_HashSet存儲自定義對象并周遊練習

package cn.itcast_03;

import java.util.HashSet;

/*
 * HashSet集合存儲自定義對象并周遊。如果成員變量的值相同即為同一個對象
 * 
 * 注意:
 *     使用的是HashSet集合,這個底層是哈希表結構。
 *     而哈希表結構底層依賴:hashCode()和equals()方法。
 *     如果你認為成員變量的值相同即為同一個對象的話,你就應該重寫這兩個方法。
 *     如何重寫呢?不用但心,自動生成即可。
 */
public class DogDemo {
  public static void main(String[] args) {
    // 建立集合對象
    HashSet<Dog> hs = new HashSet<Dog>();

    // 建立狗類對象
    Dog d1 = new Dog("大黃", 2, "黃色", '女');
    Dog d2 = new Dog("柯基", 1, "棕色", '男');
    Dog d3 = new Dog("哈士奇", 4, "黑白", '女');
    Dog d4 = new Dog("大神", 2, "黃色", '女');
    Dog d5 = new Dog("大黃", 2, "黃色", '女');

    // 元素添加到集合中
    hs.add(d1);
    hs.add(d2);
    hs.add(d3);
    hs.add(d4);
    hs.add(d5);

    // 周遊集合
    for(Dog d : hs){
      System.out.println(d.getName()+"---"+d.getAge()+"---"+d.getColor()+"---"+d.getSex());
    }
  }
}      
package cn.itcast_03;

public class Dog {
  private String name;
  private int age;
  private String color;
  private char sex;

  public Dog() {
    super();
    // TODO Auto-generated constructor stub
  }

  public Dog(String name, int age, String color, char sex) {
    super();
    this.name = name;
    this.age = age;
    this.color = color;
    this.sex = sex;
  }

  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 getColor() {
    return color;
  }

  public void setColor(String color) {
    this.color = color;
  }

  public char getSex() {
    return sex;
  }

  public void setSex(char sex) {
    this.sex = sex;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + age;
    result = prime * result + ((color == null) ? 0 : color.hashCode());
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    result = prime * result + sex;
    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 (color == null) {
      if (other.color != null)
        return false;
    } else if (!color.equals(other.color))
      return false;
    if (name == null) {
      if (other.name != null)
        return false;
    } else if (!name.equals(other.name))
      return false;
    if (sex != other.sex)
      return false;
    return true;
  }

}