I am trying to create a RetainAll method and all after scouring the forums I have found nothing that helps in my specific case. The issue I am having is that when running my program instead of retaining all the elements form a specified list and deleting all others it instead keeps the last element form the initial list.
public default boolean retainAll(Collection<?> c) {
boolean modified=false;
int index =0;
for(Object e : this) {
if(c.contains(e)==true) {
}
else if(c.contains(e)==false) {
index=this.indexOf(e);
this.remove(index);
modified = true;
}
}
return modified;
}
public default boolean remove(Object e) {
if (indexOf(e) >= 0) {
remove(indexOf(e));
return true;
}
else
return false;
}
I am just not understanding how to remove the last element.
You're modifying the collection as you iterate over it. That is generally a recipe for unhappiness.
For the standard collections, the safe way is to use an explicit iterator, and use the iterator's 'remove' method to remove the most recently returned entry.
If this is your own collection implementation you should make sure that model works for you too.
Related
while(!open.isEmpty()&& !solutionFound){
Node selected=open.poll();//fifo
State estado=selected.getState();
estado.toString();
this.exploredNodes++;
if(!explored.contains(selected.getState()) ){
if(problem.testGoal(selected.getState())){
actionSequence=recoverPath(selected, inicial);//return array with solutions
solutionFound=true;
}
//totalCost++;
successors=getSuccessors(selected);
for(Node successor : successors){
//if(!explored.contains(successor))
open.add(successor);
}
explored.add(selected.getState());
}
}
I'm trying to check if the state of the selected node is inside a hashset of nodes and if it is already in it then it shouldn't do anything.
The thing is that it always returns false. And therefore compares infinitely.
#Override
public boolean equals(Object anotherState) {
if(anotherState instanceof MazeState)return false;
if(this.life!=((MazeState)anotherState).life)return false;
if (this.position.x!=((MazeState)anotherState).position.x)return false;
if (this.position.y!=((MazeState)anotherState).position.y)return false;
if (!this.cheeses.containsAll(((MazeState)anotherState).cheeses))return false;
return true;
}
#Override
public int hashCode() {
return Objects.hash(this.position,this.life,this.cheeses);
This is my implementations of equals and hashCode which I think are fine since they compare all the attributes of the State.
Any tip would be greatly appreciated.
I think you want to apply a NOT check here.... So, the following will work
if(!(anotherState instanceof MazeState)) return false;
UPDATE
Also, a containsAll check would report two objects being equal even if the cheeses collections have elements in different order.
For my data structures class, we have to create our own Stack data type and the implementation for it as a project. The problem I'm running into is when the professor asked us to implement an equals(Object object) method. Heres what I have so far...
package stack;
import list.*;
public class Stack <E>
implements StackADT<E>//the interface
{
List <E> values;
public Stack()
{
values = new ArrayList<E>();
}
public E push(E value)
{
values.add(value);
return value;
}
public E pop()
{
return values.remove(values.size()-1);
}
public E peek()
{
return values.get(values.size()-1);
}
/** #return true only if this Stack is empty */
public boolean isEmpty()
{
return (values.size()==0);
}
/** Clear this stack, to make it an empty stack */
public void clear()
{
for (int i = 0; i < values.size()-1; i++)
{
pop();
}
}
public String toString()
{
String result = "[";
for (int i = 0; i<values.size(); i++)
{
if (i == values.size()-1)
{
result = result + values.get(i);
}
else
{
result = result + values.get(i) +",";
}
}
result = result + "]";
return result;
}
public boolean equals (Object object)
{
if (!(object instanceof StackADT))
{
return false;
}
StackADT <E> otherStack = new Stack<E>();
for(Object o: object)//heres where i run into trouble
{
otherStack.push(o);
}
for (int i=0;i<values.size()-1;i++)
{
if (!(values.get(i).equals(otherStack.pop())))
{
return false;
}
}
return true;
}
}
Our Stack is pretty much an ArrayList which we also built in our class. the problem is, I cant add the Object object into a stack because its not something thats iteratable(?able to be iterated over). Is there a better way to do this? I would think a get() would work, since the Stack I create is an ArrayList, but whenever I use get() on otherStack, it can't find the method. I had a temporary solution when I tried casting object as a stack(I hope im using the right terminology). It looked something like this
Stack otherStack = (Stack) object;
for (int i=0;i<values.size()-1;i++)
{
if (!(values.get(i).equals(otherStack.pop())))
{
return false;
}
}
return true;
}
this seemed to work, but when pop() was called on otherStack, the values in the original list(the one that becomes otherStack) that was passed into the equals() method we're also popped from the original list, leading to an incorrect result. Is there a better way to do this without adding in any other methods? I'm trying to stick as close to the formula set up by my professor as possible, so I dont want to add any extra fields or methods.
any and all help is appreciated
An equals method is not supposed to create anything, not even a temporary object. Rather than creating a new otherStack, cast the object that you have checked to be StackADT, like this:
// This should be the first line of any equals() implementation:
if (object == this) {
return true;
}
// You've got this part right: you need to check the other object's type
if (!(object instanceof StackADT)) {
return false;
}
// Now that you know the type, cast the other object to StackADT<E>
StackADT<E> otherStack = (StackADT<E>)object;
// The next step is to check the sizes:
if (values.size() != otherStack.values.size()) {
return false;
}
// Finally, go through the individual elements in a loop
In the loop that follows, do not pop the other stack. Do not do anything that can modify it. Simply go through the underlying storage (i.e. values), and check elements one by one.
Don't forget to override hashCode as well: you need to do it every time when you override equals for the object to fulfill the contract specified by java.lang.Object.
I am stuck with this code because I cannot search for t list in t.contains method.
public static <T> boolean contains(T element, List<T> t) {
if (t.isEmpty()){
return false;
} else if (t.contains(t) == element){
return true;
}
}
Please help.
Instead of
t.contains(t) == element
you probably meant to say
t.get(0) == element
which is a check whether the first list element is the one you are looking for. After you sort that out, you must sort out the recursive call. This should involve
t.subList(1, t.size())
but note that this idiom is very impractical in Java and it will result in bad performance and memory overhead.
Change it to :
public static <T> boolean contains(T element, List<T> t) {
return t.isEmpty()? false
: t.get(0).equals(element)? true
: contains(t.subList(1, t.size()));
}
Please find below my implementation for DFS.
protected void DFS(String search) {
for(Tree<T> child : leafs) {
if(child.value.equals(search))
return;
else
child.DFS(search);
System.out.println(child.value);
}
}
The objective is to stop traversal on finding the node whose value is in the variable search. However, the above function goes on traversing the tree even beyond the declared search node. Could someone help me modify the above function?
Thank you.
Edit 1
protected boolean DFS(String anaphorKey) {
boolean found = false;
for(Tree<T> child : leafs) {
if(child.head.equals(anaphorKey))
return true;
found = child.DFS(anaphorKey);
if(found == true)
break;
System.out.println(child.head);
//System.out.println("anaphorKey: "+anaphorKey);
}
return found;
}
Tried implementing the given answer suggestion (#SJuan76). The implementation above isn't working as desired. Could you point me to the place where code is not as per the logic suggested?
rookie, might I suggest an implementation using the classic for-loop (as opposed to the enhanced for-loop being used now) which allows integration of your stop-condition a bit better, something like:
protected boolean DFS(String key) {
boolean found = false;
for(int i = 0; i < leafs.size() && !found; i++) {
Tree<T> child = leafs.get(i);
if(child.head.equals(key))
found = true;
else
found = child.DFS(key);
}
return found;
}
So as soon as your found condition is hit, the 'found' becomes true and your loop stops.
What you may have forgotten is the "found = child.DFS(key)" portion of the recursion, where you need to remember the result of your recursive calls so ALL your for-loops on up the chain all break as soon as you return.
Hope that helps.
Option A (Nice): the function returns a value, when the node is found it returns a different value that if the node was not found. When you call to method, if you get the found value you stop the loop and return the found value too.
Option B (Ugly): When found, thow an Exception (better if it is your own implementation of it). Don't forget to catch it.
Option C (Uglier): The same with global (static) variables.
UPDATE 1:
It looks like your method should run ok now, can you check (System.out.println) if your value is ever found?
In a more personal opinion, I would find
protected boolean DFS(String anaphorKey) {
for(Tree<T> child : leafs) {
if(child.head.equals(anaphorKey))
return true;
if(child.DFS(anaphorKey)) // No need to store value. No need to check == true (it is implicit)
return true; // If we are in this line the value was found, always return true
System.out.println(child.head);
//System.out.println("anaphorKey: "+anaphorKey);
}
return false; // If the method did not exit previously it was because the value was not found, so in this line always return false
}
more readable (but it should work exactly as your implementation)
I've created my own Stack class but need to implement a get method to return a stack element based on an index passed within the args. I've created a contains method and would of assumed get would work in a similar fashion.
My question is how would I implement the get method? I want to basically implement the get method that Stack inherits from the Vector class in the standard library. See -http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Vector.html#get%28int%29
Here is my contains method below.
public boolean contains (T value){
T t = top.item;
Object node = t;
while(node!=null)
{
if(node==value){
return true;
}
else {
node=top.next;
}
}
return false;
}
The classical Stack does not support that operation, and truly should not extend Vector.
The operations that it supports are:
push(item)
pop();
peek();
So what you want to do, if you want to use a data structure to back your Stack is to use an instance of a List which will allow you to mirror what the original Sun team did.
function contains(Item item)
{
return Stack.getList().contains(item)
}
If instead you want to just use an array as the backing you would need to iterate over each value in the array and perform an equals comparison on it.
function contains(Item item)
{
for(int i = 0; i < itemArray.length;i++)
{
if(itemArray[i] == item)
{
return true;
}
}
return false;
}