HashSet實現了Set接口,是無序集合沒有索引,無重複元素;
hashCode()方法是十進制整數,系統模擬出的邏輯地址值,不是對象的物理地址值;
整型返回的hashCode值根據源碼:
Integer num = 123;
System.out.println(num.hashCode()); //123
public static int hashCode(int value) {
return value;
}
布爾值返回的hashCode值根據源碼:
Boolean ff = false;
System.out.println(ff.hashCode()); //1237
public static int hashCode(boolean value) {
return value ? 1231 : 1237;
}
引用類型返回的hashCode值根據源碼:
String s1 = "abc";
System.out.println(s1.hashCode()); //96354
public int hashCode() {
int h = hash; //default is 0
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;
}
引用類型計算方法:
//分別先取出a、b、c對應的ascii碼值對應val[]的值
System.out.println((int)'a'); //97
System.out.println((int)'b'); //98
System.out.println((int)'c'); //99
//字符串abc長度爲3,循環次數3次,h參數對應hash根據源碼查看默認爲0
//第一次循環:h = 31 * h + val[i];
31 * 0 + 97 = 97
//第二次循環:h = 31 * h + val[i];
31 * 97 + 98 = 3105
//第三次循環:h = 31 * h + val[i];
31 * 3105 + 99 = 96354