I'm trying to store a set of possible choices and eliminate duplicates so I'm storing the choices I've made in a HashSet
. I have two pieces of data for each step and the combination of both must not be unique in order for it to be considered a duplicate (e.g. [2,0], [0,2], [2,2] would all be new steps but then going to [2,2] would be a duplicate).
I believe I need to override equals
in order to properly determine if the step is already in the HashSet
but I am not using a custom class, just an array of Integers
, so most of what I've found isn't applicable (to my knowledge). This seems like it may be useful, suggesting the possibility of subclassing HashSet
but I'd like to avoid that if possible. I was hoping the equals
method I have commented out would work but it was never called. Do I need to override hashCode()
as well? I know they go hand in hand. Do I just need to go write my own class or is there another method of doing what I want?
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
}
}
}
}