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