public static void main(String[] args) {
int[] nums = new int[7];
nums[0] = 3;
nums[1] = 7;
nums[2] = 6;
nums[3] = 6;
nums[4] = 7;
nums[5] = 8;
nums[6] = 9;
Set<Integer> set = new HashSet();
for (int i = 0; i < 7; i++){
set.add(nums[i]);
System.out.println(set);
}
System.out.println();
System.out.println(set);
代码如上,按道理来说应该输出3,7,6,8,9,但是输出3,6,7,8,9
于是我一开始以为是后面那个7覆盖掉了前面那个7,但是根据每次输出一个set发现,在输入第三个数字6得时候,就自动将其排序至7得前面了。于是我很奇怪,不是说hashset是无序的吗?为什么会将6排序至7前面呢?答案在HashSet的源码里,详见
优快云上已有的博客,源码我还在研究中
而且如果输入字符类型(char) 也是一样的结果,字符类型存储的是数字。目前不知道是为什么。有时间再看hashset关于char类型的源码,先继续刷题
运行以上代码会得到和int型一样的结果