简体   繁体   English

根据对象的内容创建唯一的ID

[英]Create an unique ID based on the content of the object

i would like to know if it is possible in java,to create an ID for an element inside an object, so if another object is generated with the same element i can check if it was created priviously. 我想知道是否有可能在Java中为对象内的一个元素创建一个ID,因此,如果使用相同的元素生成了另一个对象,我可以检查它是否是私有创建的。

Example1 ` 例子1

{

    int[][] cha = new int[3][3];
    cha[0][0] = 8;
    cha[0][1] = 1;
    cha[0][2] = 3;
    cha[1][0] = 4;
    cha[1][1] = 0;
    cha[1][2] = 2;
    cha[2][0] = 7;
    cha[2][1] = 6;
    cha[2][2] = 5;

    int[][] hol = new int[3][3];
    hol[0][0] = 8;
    hol[0][1] = 1;
    hol[0][2] = 3;
    hol[1][0] = 4;
    hol[1][1] = 0;
    hol[1][2] = 2;
    hol[2][0] = 7;
    hol[2][1] = 6;
    hol[2][2] = 5;


    HashSet<int[][]> k = new HashSet();
    k.add(cha);

    System.out.println(k.contains(cha));
    System.out.println(k.contains(hol));


}`

In this case, I wil get the values "true, false" even though both matrix are the same ( I know it is because HashSet does reference to the memory address and not the object.) 在这种情况下,即使两个矩阵都相同,我也将获得值“ true,false”(我知道这是因为HashSet确实引用了内存地址而不是对象)。

I want to be able to create the matrix a second time and determinate if it was already created. 我希望能够再次创建矩阵,并确定是否已经创建矩阵。

Thanks. 谢谢。

将其包装在类中,并定义自己的equals()hashcode()

I know it is because HashSet does reference to the memory address and not the object 我知道这是因为HashSet确实引用了内存地址而不是对象

No, that's not the reason. 不,那不是原因。 The reason is that an array is only equal to itself, because arrays don't override the Object.equals() and Object.hashCode() methods, that HashSet uses to check which elements it already contains. 原因是数组仅等于其自身,因为数组不会覆盖Object.equals()Object.hashCode()方法,而HashSet会使用该方法检查其已包含的元素。

To get the behavior you want, you need to wrap the matrix into your own class which overrides equals() and hashCode(), in order to tell when two matrices are equal. 为了获得所需的行为,您需要将矩阵包装到自己的类中,该类重写equals()和hashCode(),以便确定两个矩阵何时相等。 Make sure to never modify any element of a matrix once it has been stored into the HashSet: 一旦将矩阵的任何元素存储到HashSet中,请确保不要修改它:

public final class Matrix {
    private int[][] elements;

    public Matrix(int[][] elements) {
        this.elements = elements; 
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Matrix)) {
            return false;
        }
        Matrix m = (Matrix) o;
        return Arrays.deepEquals(this.elements, m.elements);
    }

    @Override
    public int hashCode() {
        return Arrays.deepHashCode(elements);
    }
}

And now you can do 现在你可以做

HashSet<Matrix> set = new HashSet<>();

Matrix m1 = new Matrix(cha);
k.add(m1);

System.out.println(set.contains(m1));

Matrix m2 = new Matrix(hol);
System.out.println(set.contains(m2));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM