提问者:小点点

获取非重写的equals方法以使用hashCode


这是来自与hashCode一起使用的旧版本代码并等于,但我正在尝试让新版本使用它。我认为原因是因为在旧版本中我覆盖了 equals 和 hashCode,但在新版本中我似乎无法做到这一点,因为我不再比较对象,而是比较数组(这是猜测)。因此,当前版本不会拾取重复项。它说没有重复项,但这是不正确的。

以下是检测重复项的旧版本的哈希代码和等于。

private Cube() {
    cube = new int[][] {
        { 0, 0, 0, 0 },
        { 1, 1, 1, 1 },
        { 2, 2, 2, 2 },
        { 3, 3, 3, 3 },
        { 4, 4, 4, 4 },
        { 5, 5, 5, 5 }
    };

    cube = scanCube(cube);
    cube = print_cube(cube);
}

private Cube(Cube other) {
    cube = new int[other.cube.length][];
    for (int i = 0; i < other.cube.length; i++) {
        cube[i] = Arrays.copyOf(other.cube[i], other.cube[i].length);
    }
}

public boolean isSolved() {
    for (int i = 0; i < cube.length; i++) {
        for (int k = 1; k < cube[i].length; k++) {
            if (cube[i][0] != cube[i][k]) {
                return false;
            }
        }
    }
    return true;
}

@Override
public boolean equals(Object other) {
    return other instanceof Cube && Arrays.deepEquals(((Cube) other).cube, cube);
}


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

这是当前版本。

public static void main(String[] args) {

    int[][] cube = new int[][] {
        { 0, 0, 0, 0 },
        { 1, 1, 1, 1 },
        { 2, 2, 2, 2 },
        { 3, 3, 3, 3 },
        { 4, 4, 4, 4 },
        { 5, 5, 5, 5 }
    };
    cube = scanCube(cube);
    cube = print_cube(cube);
    solve(cube);
}     
private static boolean isSolved(int [][] cube) {
    for (int i = 0; i < cube.length; i++) {
        for (int k = 1; k < cube[i].length; k++) {
            if (cube[i][0] != cube[i][k]) {
                return false;
            }
        }
    }
    return true;
}

public static int[][] copyCube(int [][] cube){
   int [][] copy = new int [6][4];

   for(int i = 0; i < 6; i++ ){
       copy[i] = cube[i].clone();
   }
   return copy;
}

public static boolean equals(int[][] other, int[][] cube) {
    return Arrays.deepEquals(other, cube);
}

public int hashCode(int [][] cube) {
    return Arrays.deepHashCode(cube);
}

在搜索方法中是确定重复项的地方。这是旧的代码。

static public void solve(Cube c) {
    Set<Cube> cubesFound = new HashSet<Cube>();
    cubesFound.add(c);

    Stack<Cube> s = new Stack<Cube>();
    s.push(c);

    Set<Stack<Cube>> initialPaths = new HashSet<Stack<Cube>>();
    initialPaths.add(s);

    solve(initialPaths, cubesFound);
}

static public void solve(Set<Stack<Cube>> livePaths, Set<Cube> cubesFoundSoFar) {
    System.out.println("livePaths size:" + livePaths.size());
    int numDupes = 0;

    Set<Stack<Cube>> newLivePaths = new HashSet<Stack<Cube>>();

    for (Stack<Cube> currentPath : livePaths) {

        Set<Cube> nextStates = currentPath.peek().getNextStates();

        for (Cube next : nextStates) {
            if (currentPath.size() > 1 && next.isSolved()) {
                currentPath.push(next);
                System.out.println("Path length:" + currentPath.size());
                System.out.println("Path:" + currentPath);
                System.exit(0);

            } else if (!cubesFoundSoFar.contains(next)) {
                Stack<Cube> newCurrentPath = new Stack<Cube>();
                newCurrentPath.addAll(currentPath);
                newCurrentPath.push(next);
                newLivePaths.add(newCurrentPath);
                cubesFoundSoFar.add(next);
            } else {
                numDupes += 1;
            }
        }
    }

    System.out.println("Duplicates found " + numDupes + ".");
    solve(newLivePaths, cubesFoundSoFar);
}

还有新的。

static private void solve(int[][] cube) {

    int[][][] s = new int[12][6][4];
    s[0] = cube;

    Set<int[][][]> initialPaths = new HashSet<int[][][]>();
    initialPaths.add(s);
    Set<int[][]> cubesFound = new HashSet<int[][]>();
    cubesFound.add(cube);

    solve(initialPaths, cubesFound, 1);
}

static private void solve(Set<int[][][]> livePaths,Set<int[][]> cubesFoundSoFar, int iterationCount) {
    System.out.println("livePaths size:" + livePaths.size());

    Set<int[][][]> newLivePaths = new HashSet<int[][][]>();
    int counter = 0;
    int recordDepth = 0;
    int duplicates = 0;

    for(int[][][] currentPath : livePaths) {

        Set<int [][]> nextStates = getNextStates(currentPath[iterationCount-1]);

        for (int[][] next : nextStates) {
            if (isSolved(next)) {
                currentPath[iterationCount] = next;
                int maxSteps = -1;
                System.out.println("Path:" );
                for(int i = 0; i < currentPath.length; i++) {
                    if(currentPath[i] != null) {
                        maxSteps = i;
                        System.out.println(toString(currentPath[i]));
                    }else {
                        break;
                    }
                }
                System.out.println("Path length:" + maxSteps);
                System.exit(0);

            } else if(!cubesFoundSoFar.contains(next)){
                int[][][] newCurrentPath = new int[12][6][4];
                newCurrentPath = currentPath.clone();
                newCurrentPath[iterationCount] = next;
                newLivePaths.add(newCurrentPath);
                counter ++;
                cubesFoundSoFar.add(next);
            }  else {
                duplicates += 1;
            }
        }
    }
    //System.out.println(" Set.size(): "+newLivePaths.size());

    String storeStates = "positions.txt";
    try {
        PrintWriter outputStream = new PrintWriter(storeStates);
        outputStream.println(storeStates);
        for(int[][][] s:newLivePaths) {
            outputStream.println(toString(s[iterationCount]));
        }
        outputStream.close();

    } catch (FileNotFoundException e) {
        System.err.println("Fatal: could not open cache file for cube positions. exiting.");
        e.printStackTrace();
        System.exit(1);
    }
    System.out.println("Duplicates found "+ duplicates + ".");
    solve(newLivePaths, cubesFoundSoFar, iterationCount+1);
}

共1个答案

匿名用户

您没有在第二个代码中重写< code>equals(Object)方法,但是< code > set . contains(Object)使用< code>equals来比较元素。因为多维数据集中没有对象,所以使用< code>Object的对象。这并不比较内容,它只是测试对象是否是相同的实例(相同的内存位置)。

此处的相关部分包含

...更正式地说,当且仅当此集合包含元素 e 时返回 true,使得 (o==null ? e==null : o.equals(e))。...

您可以在第二个代码中添加类似的内容:

@Override
public boolean equals(Object other) {
    if (other instanceof Cube)
        return equals(cube, ((Cube) other).cube);
    else
        return false;
}


@Override
public int hashCode() {
    return hashCode(cube);
}