HashSet集合的特点:元素是具备唯一性的,每次存储都要先算出哈希值,看有没相同,没有相同的存储到相应的位置,如果相同则再判断存储进来的值是否与被比较的相同,如果相同,则不再存储,不同就存储
package com.java.b.customer.www;
public class Customer {
private String name;
private int age;
public Customer() {
super();
}
public Customer(String name, int age) {
super();
this.name = name;
this.age = age;
}
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;
}
@Override
public String toString() {
return "Customer [name=" + name + ", age=" + age + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.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;
Customer other = (Customer) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
package com.java.c.set.www;
import java.util.HashSet;
import java.util.Iterator;
import com.java.b.customer.www.Customer;
public class HashSetDmeo {
public static void main(String[] args) {
//创建一个hashSet容器
HashSet set=new HashSet();
//添加元素
set.add(new Customer("小张1",25));
set.add(new Customer("小李2",20));
set.add(new Customer("小李4",29));
set.add(new Customer("小火5",17));
set.add(new Customer("小李2",20));
for (Iterator it = set.iterator(); it.hasNext();) {
System.out.println(it.next());
}
}
}