set:
如果是實現(xiàn)了Set接口的集合類幔亥,具備的特點: 無序,不可重復(fù)
public class Demo1 {
public static void main(String[] args) {
Set set = new HashSet();
set.add("王五");
set.add("張三");
set.add("李四");
System.out.println("添加成功嗎?"+set.add("李四"));
System.out.println(set);
}
}
hashSet的實現(xiàn)原理:
往Haset添加元素的時候,HashSet會先調(diào)用元素的hashCode方法得到元素的哈希值 谋旦,
然后通過元素 的哈希值經(jīng)過移位等運算,就可以算出該元素在哈希表中 的存儲位置骗随。
情況1: 如果算出元素存儲的位置目前沒有任何元素存儲蛤织,那么該元素可以直接存儲到該位置上。
情況2: 如果算出該元素的存儲位置目前已經(jīng)存在有其他的元素了鸿染,那么會調(diào)用該元素的equals方法與該位置的元素再比較一次
指蚜,如果equals返回的是true,那么該元素與這個位置上的元素就視為重復(fù)元素涨椒,不允許添加摊鸡,如果equals方法返回的是false,那么該元素運行 添加蚕冬。
class Person{
int id;
String name;
public Person(int id, String name) {
super();
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "{ 編號:"+ this.id+" 姓名:"+ this.name+"}";
}
@Override
public int hashCode() {
System.out.println("=======hashCode=====");
return this.id;
}
@Override
public boolean equals(Object obj) {
System.out.println("======equals======");
Person p = (Person)obj;
return this.id==p.id;
}
}
public class Demo2 {
public static void main(String[] args) {
/*
HashSet set = new HashSet();
set.add("狗娃");
set.add("狗剩");
set.add("鐵蛋");
System.out.println("集合的元素:"+ set);
*/
HashSet set = new HashSet();
set.add(new Person(110,"狗娃"));
set.add(new Person(220,"狗剩"));
set.add(new Person(330,"鐵蛋"));
//在現(xiàn)實生活中只要編號一致就為同一個人.
System.out.println("添加成功嗎免猾?"+set.add(new Person(110,"狗娃")));
System.out.println("集合的元素:"+set);
}
}
HashSet的存儲原理.png
應(yīng)用:
使用HashSet添加用戶,如果用戶名就認為是重復(fù)元素
import java.util.*;
class Account{
String name;
String passwd;
Account(String name,String passwd){
this.name = name;
this.passwd = passwd;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return this.name.hashCode();
}
@Override
public boolean equals(Object arg0) {
Account act = (Account)arg0;
if (this.name.equals(act.name))
return true;
return false;
}
}
public class Test02 {
public static void main(String[] args) {
HashSet set = new HashSet();
while(true){
System.out.println("請輸入用戶名和密碼:");
String name = new Scanner(System.in).nextLine();
String passwd = new Scanner(System.in).nextLine();
boolean result = set.add(new Account(name,passwd));
if (result){
System.out.println("注冊成功");
}else{
System.out.println("該用戶已存在");
}
}
}
}
這里補充一個問題
"aa".hashCode();
new String("aa").hashCode();
兩者之間的hashCode是一樣的,為什么呢?
因為String類重寫了hashCode方法,用每個字符去計算最后得出來的haskCode值;所以只要是字符串內(nèi)容一樣,那么調(diào)用haskCode方法得到的hask值肯定是一樣的
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}