简体   繁体   中英

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.

Example1 `

{

    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.)

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

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.

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. Make sure to never modify any element of a matrix once it has been stored into the 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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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