john
john

Reputation: 65

Java LinkedList Search

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);

Upvotes: 3

Views: 115

Answers (3)

MrSimpleMind
MrSimpleMind

Reputation: 8587

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;
    }
}

Upvotes: 0

javadesigner
javadesigner

Reputation: 33

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.

Upvotes: 0

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23329

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

Upvotes: 2

Related Questions