I. McFee
I. McFee

Reputation: 33

Search linkedlist for object variable

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

Upvotes: 1

Views: 176

Answers (1)

StaticBeagle
StaticBeagle

Reputation: 5175

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

Upvotes: 2

Related Questions