gpt4 book ai didi

java - 在多个二维数组中搜索相似条目的代码

转载 作者:行者123 更新时间:2023-12-02 00:32:05 24 4
gpt4 key购买 nike

我正在尝试为 my previous topic 中描述的问题编写代码。建议的解决方案是使用 HashMap 在多个数组中查找相似的条目(数组具有相同的列数,但它们可能具有不同的行数)。

下面是我的示例代码,基于用户 John B 提供的代码片段 here 。为了简单起见和调试目的,我只创建了 3 个不同的一维行而不是二维数组。另外,为了简单起见,函数 equalRows 应返回 truefalse 而不是行索引。

因此,在下面的代码中,函数 equalRows 应该返回 false,因为 array3{1,3,4} 并且它确实有 {1,2,3}。相反,该函数返回true。为什么会发生这种情况?

import java.util.HashMap;
import java.util.Map;

public class Test {

public static void main(String[] args) {
int[] array1 = {1,2,3};
int[] array2 = {1,2,3};
int[] array3 = {1,3,4};
boolean answ = equalRows(array1,array2,array3);
System.out.println(answ);
}

static class Row extends Object {
private int value;
private volatile int hashCode = 0;

public Row(int val) {
this.value = val;
}

@Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if((obj == null) || (obj.getClass() != this.getClass()))
return false;
// object must be Row at this point
Row row = (Row)obj;
return (value == row.value);
}

@Override
public int hashCode () {
final int multiplier = 7;
if (hashCode == 0) {
int code = 31;
code = multiplier * code + value;
hashCode = code;
}
return hashCode;
}
}

private static Map<Row, Integer> map(int[] array) {
Map<Row, Integer> arrayMap = new HashMap<Row, Integer>();
for (int i=0; i<array.length; i++)
arrayMap.put(new Row(array[i]), i);
return arrayMap;
}

private static boolean equalRows(int[] array1, int[] array2, int[] array3){
Map<Row, Integer> map1 = map(array1);
Map<Row, Integer> map2 = map(array2);

for (int i=0; i<array3.length; i++){
Row row = new Row(array3[i]);
Integer array1Row = map1.get(row);
Integer array2Row = map2.get(row);
if (array1Row != null || array2Row != null) {
return false;
}
}
return true;
}

}

编辑#1代码已根据建议的解决方案进行更新。

编辑#2我检查了建议的解决方案,但该函数甚至返回 false: int[] array1 = {1,2,3}; int[] array2 = {1,2,3}; int[] array3 = {1,2,3},尽管它应该是正确的。我认为问题出在函数 hashcode 上。那么,有什么解决办法吗?

最佳答案

这行是错误的,它立即返回true:

if (array1Row != null && array2Row != null) {
return true;
}

你必须做的是这个(完全颠倒逻辑):

if (array1Row == null || array2Row == null) {
return false;
}

关于java - 在多个二维数组中搜索相似条目的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8789979/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com