3

i have this linked list:

LinkedList<Cookies> linkList = new LinkedList<>();
linkList.add(new Cookies("Name1", 2, 2));
linkList.add(new Cookies("Name2", 3, 1));
linkList.add(new Cookies("Name3", 1, 6));
linkList.add(new Cookies("Name4", 2, 2));
linkList.add(new Cookies("Name2", 4, 2));

how would i do a search for "Name2" and output:

Name2, 3, 1
Name2, 4, 2

i have done this but it returns false/not found

boolean found = linkList.contains(new Cookies("Name2", 3, 1));
System.out.println("Found: " + found);
john
  • 65
  • 3
  • If Cookies is a user defined class, have you created a comparator for that class? The reason it returns false is because you have created a completely separate object. Even though that new object has the same data contained within it, it is not the same object as the one in your list. That's like saying two separate apples with the same qualities (shape, size, colour) are the same apple. – Taelsin Nov 20 '15 at 00:38
  • Possible duplicate of [Java List.contains(Object with field value equal to x)](http://stackoverflow.com/questions/18852059/java-list-containsobject-with-field-value-equal-to-x) – Adrian Nov 20 '15 at 00:42

3 Answers3

2

You need to implement the equals method in the Cookies class so linkList.contains works as you expect

class Cookie{
   @Override
   boolean equals(Object cookie){
   ..
  }
}

Otherwise Object.equals will be called which checks for reference equality, which means

linkList.contains(new Cookies("Name2", 3, 1)); 

is always false

Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77
0

You have to implement the equals() method in your Cookie class, to return true, if two Cookie objects contain the same values (or at the very least, the same Name).

Also, implement the hashCode() method to return the same value for Cookie objects, if equals() would return true.

0

If this is your start to learn Java then I guess the meaning of this is to learn how lists work and how to loop a list and override a toString etc.

An example is shown below.

import java.util.*;

public class TTT {
  public static void main(String[] argv) {
    LinkedList<Cookies> linkList = new LinkedList<>();
    linkList.add(new Cookies("Name1", 2, 2));
    linkList.add(new Cookies("Name2", 3, 1));
    linkList.add(new Cookies("Name3", 1, 6));
    linkList.add(new Cookies("Name4", 2, 2));
    linkList.add(new Cookies("Name2", 4, 2));

    for(int i=0; i<linkList.size(); i++ ) {
        Cookies c = linkList.get(i);
        if( c.getName().equals("Name2")) {
          System.out.println(c);
        }
    }
  }
}

class Cookies {
    String n;
    int a;
    int b;

    public Cookies(String n, int a, int b) {
      this.n = n;
      this.a = a;
      this.b = b;
    }

    public String getName() {
        return n;
    }

    public String toString() {
        return n+", " + a + ", " + b;
    }
}
MrSimpleMind
  • 7,890
  • 3
  • 40
  • 45