I need to search a LinkedList and compare the objects in the list so I don't add duplicates. I can't figure out how to pull a node so I can compare it to the StudentInfo object I'm trying to add. This is my attempt to use an iterator:
private LinkedList<CourseInfo> classes = new LinkedList<>();
public void addCourse(String cid, String name, String prof, String days,
String time, String room)
{
CourseInfo course = new CourseInfo(cid, name, prof, days, time, room);
Iterator i = classes.iterator();
while(i.hasNext())
{
if(i.equals(course))
{
System.out.println("Caught");
break;
}
}
}
I specifically need to compare the cid variables
1 Answer 1
Minor note, traversing a LinkedList
to check if an element exists is expensive. You might want to consider HashSet
. That being said, in your code you are comparing the iterator
with the CourseInfo
, you need to compare the element pointed by the iterator
instead by using next()
. Also, next()
is required in order to advance the iterator (thanks to Code-Apprentice for the suggestion) otherwise you could end up in an infinite loop in i.hasNext()
.
private LinkedList<CourseInfo> classes = new LinkedList<>();
public void addCourse(String cid, String name, String prof, String days,
String time, String room)
{
CourseInfo course = new CourseInfo(cid, name, prof, days, time, room);
// Don't use raw types e.g. Iterator it
// Specify the type of element you are iterating on
// Iterator<T> it
Iterator<CourseInfo> i = classes.iterator();
while(i.hasNext())
{
CourseInfo cInfo = i.next(); // get the element pointed by the iterator
if(cInfo.equals(course))
{
System.out.println("Caught");
break;
}
}
}
Or using enhanced for-loops:
for(CourseInfo ci : classes) {
if(ci.equals(course)) {
System.out.println("Caught");
break;
}
}
-
it says incompatible types: Object cannot be converted to CourseInfoI. McFee– I. McFee06/18/2018 23:23:35Commented Jun 18, 2018 at 23:23
-
1
tmp
is probably the worst imaginable variable name.David Conrad– David Conrad06/18/2018 23:36:18Commented Jun 18, 2018 at 23:36 -
1Note that the call to
next()
is required in order to advance the iterator. The original while loop would continue indefinitely without this.Code-Apprentice– Code-Apprentice06/18/2018 23:40:28Commented Jun 18, 2018 at 23:40 -
2@I.McFee You should edit your question with an update so that you can format the code correctly. This answer assumes that you already overrode the
equals()
andhashcode()
method correctly.Code-Apprentice– Code-Apprentice06/18/2018 23:52:49Commented Jun 18, 2018 at 23:52 -
1@I.McFee are you overriding equals & hashcode for
CourseInfo
?StaticBeagle– StaticBeagle06/18/2018 23:54:26Commented Jun 18, 2018 at 23:54
HashSet
. Find an object:list.contains(...)
.equals()
andhashcode()
in yourCourseInfo
class?