0
public class LinkedBag<T> implements BagInterface<T>{
    private Node firstNode;
    private int numberOfEntries;

    public LinkedBag() {
      firstNode = null;
      numberOfEntries = 0;
    }


    public int getCurrentSize(){
       return numberOfEntries;
    }
}


public static class  Node<T> {
    private T data;
    private Node<T> next;
    public Node(T dataPortion, Node<T> nextNode) {
        data = dataPortion;
        next = nextNode;
    } // end constructor
    public Node(T dataPortion) {
        this(dataPortion, null);
    } // end constructor
    public Node<T> getNext() {
        return next;
    }
    public void setNext(Node<T> newNext) {
        next = newNext;
    }
    public T getData() {
        return data;
    }
    public void setData(T data) {
        this.data = data;
    }
}

//Answer:

public boolean addLikeASet (T anEntry) {
    if(anEntry == null) {
        return false;
    }
    else if(firstNode == null){
         firstNode.setData(anEntry);
        return true;
    }
    
    else if(firstNode.data == anEntry){
        return false;
    }
    
    Node n = firstNode;
    while(n.next != null){
        n = n.next;
        if(n.data == anEntry){
            return false;
        }
     
        
    }
    
    n.setData(anEntry);
    
    return true;
        

I am trying to create a method called addLikeASet where it adds anEntry to the Node only if there isn't pre-existing data that equals the parameter "anEntry" in which case it will return false

For example, if a LinkedBag contained "A", "B", and "C":

Calling addLikeASet("D") would return true and add "D" to the LinkedBag.

  • However, calling addLikeASet("C")would return `false` and no value would be added.

Still, my code only works partially and doesn't cover all the possibilities.

Progman
  • 16,827
  • 6
  • 33
  • 48
NoobCoder
  • 5
  • 1
  • Does this answer your question? [Compare two objects with .equals() and == operator](https://stackoverflow.com/questions/13387742/compare-two-objects-with-equals-and-operator) – Progman Feb 11 '23 at 11:02

1 Answers1

0

Your solution using == only works with primitives.

Yo have to change it to use Object.equals:

if(n.data.equals(anEntry)){
    return false;
}

Obviously the objects being stored have to implement equals and hashcode() for this to work.

Bill Mair
  • 1,073
  • 6
  • 15