如何设置检查重复项? Java HashSet [英] How Set checks for duplicates? Java HashSet

查看:74
本文介绍了如何设置检查重复项? Java HashSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下代码,它输出"1".第二个代码输出"2",我不明白为什么会这样.是因为我要添加相同的对象吗?我应该如何实现所需的输出2.

For the below code it outputs " 1 ". and second code outputs " 2 " I don't understand why this is happening. Is it because I am adding the same object? How should I achieve the desired output 2.

import java.util.*;
public class maptest {
public static void main(String[] args) {
    Set<Integer[]> set = new HashSet<Integer[]>();
    Integer[] t = new Integer[2];
    t[0] = t[1] = 1;
    set.add(t);
    Integer[] t1 = new Integer[2];
    t[0] = t[1] = 0;
    set.add(t);
    System.out.println(set.size());

   }
}

第二个代码:

import java.util.*;
public class maptest {
public static void main(String[] args) {
    Set<Integer[]> set = new HashSet<Integer[]>();
    Integer[] t = new Integer[2];
    t[0] = t[1] = 1;
    set.add(t);
    Integer[] t1 = new Integer[2];
    t1[0] = t1[1] = 1;
    set.add(t1);
    System.out.println(set.size());

    }
}

推荐答案

Set实现可能调用t.hashCode(),并且由于数组不会覆盖 Arrays.hashCode .

The Set implementation probably calls t.hashCode() and since arrays don't override the Object.hashCode method, the same object will have the same hashcode. Changing the array's contents thus does not affect its hash code. To get an array's hash code correctly, you should call Arrays.hashCode.

无论如何,您都不应该真正将可变的东西放入集合中,所以我建议您将不可变的列表放入集合中.如果要坚持使用数组,只需像使用t1一样创建一个新数组,然后将其放入集合中即可.

You shouldn't really put mutable things inside sets anyways, so I would suggest you put immutable lists into sets instead. If you want to stick with arrays, just create a new array, like you did with t1, and put it into the set.

对于代码2,tt1是两个不同的数组,因此它们的哈希码不同.同样,由于hashCode方法未在数组中覆盖.数组的内容不影响哈希码,无论它们是否相同.

For code 2, t and t1 are two different arrays so their hash code are different. Again, since the hashCode method is not overridden in arrays. The array's contents don't effect the hash code, whether or not they are the same.

这篇关于如何设置检查重复项? Java HashSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆