Im having trouble keeping track of nodes in my stack. My nodes contain a 2d int array which contains numbers 0-20 as well as another integer measuring the cost to get to the current node state (2d int array).
currently i cant figure out how to track if my stack contains a node that i wish to skip since it is already in the stack or has been popped before so i avoid repeating the same compares on nodes that have the exact same state + costs.
if q is my stack and n1 is my current node i just popped, why wont
q.contains(n1);
ever return true?
I also tried making an ArrayList which creates a string for every node
Ex
1 2 4
5 3 6
0 7 8
Creates the string "1,2,4,5,3,6,0,7,8,". if i add this string to the array list and i use aList.contains(stringKey); never returns true?
I think i have to do something with an object because the contains() requires an object to be passed, and im not 100% sure how to do this.
The contains(obj)
of any list returns true
if it found obj
in its list. It checks each object
in list with the obj
that you have provided with equals()
method. So you need to override the equals()
method of the object that you are using.
Example :
class MyObj {
int a;
char b;
MyObj(int a, char b) {
this.a = a; this.b = b;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof MyObj){
MyObj myobj = (MyObj) obj;
if(myobj.a == a && myobj.b == b){
return true;
}
}
return false;
}
}
Now it can be used in any List
as here :
ArrayList<MyObj> list = new ArrayList<>();
MyObj obj = new MyObj(3, 'b');
list.add(obj);
System.out.println(list.contains(obj));
System.out.println(list.contains(new MyObj(3, 'b')));
Output :
true
true
According to good design pattern we should override hashCode()
too when we decides to override equals()
.