【发布时间】:2013-05-18 21:19:54
【问题描述】:
我正在尝试存储一组可能的选择并消除重复项,因此我将我所做的选择存储在 HashSet 中。我的每一步都有两条数据,两者的组合不能唯一,这样才能被认为是重复的(例如 [2,0]、[0,2]、[2,2] 都是新的步骤,但随后转到 [2,2] 将是重复的)。
我相信我需要重写 equals 以正确确定步骤是否已经在 HashSet 但我没有使用自定义类,只是 Integers 的数组,所以我的大部分内容发现不适用(据我所知)。 This seems like it may be useful,建议子类化HashSet 的可能性,但如果可能的话,我想避免这种情况。我希望我注释掉的equals 方法可以工作,但它从未被调用过。我是否也需要覆盖hashCode()?我知道他们齐头并进。我只需要编写自己的课程还是有其他方法可以做我想做的事?
import java.util.HashSet;
public class EP2 {
public static long count = 0;
public static HashSet<Integer []> visits = new HashSet<Integer []>();
//@Override
//public boolean equals(Object j){
// return true;
//}
public static void main(String[] args) {
int position = 0;
int depth = 0;
walk(position, depth);
System.out.println(count);
}
public static void walk(int position, int depth){
count++;
Integer[] specs = new Integer[2];
specs[0] = position;
specs[1] = depth;
visits.add(specs);
Integer[] specL = new Integer[]{position - 1, depth+1};
Integer[] specR = new Integer[]{position + 1, depth+1};
//doesn't avoid [0,2] duplicates
if(depth < 2){
if(!visits.contains(specL)){
walk(position - 1, depth+1); //walk left
}
if(!visits.contains(specR)){
walk(position + 1, depth+1); //walk right
}
}
}
}
【问题讨论】:
-
听起来像只使用Point 可能会满足您的需求。
-
我不明白。为什么不能简单地用一对
ints 创建一个新类? -
我不知道它存在,但在这种情况下是的,我可以接受。谢谢。但是,我仍然希望回答这个问题
-
@BalázsMáriaNémeth 我可以,但我很好奇以当前的方式解决问题。那样我不会学到那么多。
-
但是这个问题对我来说并没有真正的意义。您不能覆盖 Integer[] 的
equals,因为那甚至不是一个类 :)
标签: java equals contains hashset overriding