I am trying to do a linear search of a linked list
. One search is by int
and the other String
. What am I doing wrong? **Updated the code based on recommendations.
Within the main
public static LinkedList<Contributor> contributorList = new LinkedList<>();
String searchKey = "Jones";
int intSearchKey = 45;
System.out.println("Search key " + searchKey + " is found? " + sequentialSearch(contributorList, searchKey));
System.out.println("Search key " + intSearchKey + " is found? " + sequentialSearch(contributorList, intSearchKey));
Called methods
public static <Contributor> boolean sequentialSearch(Iterable<Contributor> contributorList, int intSearchKey) {
Iterator<Contributor> iter = contributorList.iterator();
while (iter.hasNext()) {
if (iter.next().equals(intSearchKey)) {
return true;
}
iter = (Iterator<Contributor>) iter.next();
}
return false;
}
public static <Contributor> boolean sequentialSearch(Iterable<Contributor> contributorList, String searchKey) {
Iterator<Contributor> iter = contributorList.iterator();
while (iter.hasNext()) {
if (iter.next().equals(searchKey)) {
return true;
}
iter = (Iterator<Contributor>) iter.next();
}
return false;
}
This line compares a Contributor object to a String.
if (iter.next().equals(searchKey)) {
Without seeing Contributor object, I'm guessing you want something like this
if (iter.next().getKey().equals(searchKey)) {
Also, this line makes no sense:
iter = (Iterator<Contributor>) iter.next();
iter.next() returns the element type, not an iterator