0

I am trying to understand what's this line doing:

Set<ListNode> nodesSeen = new HashSet<>();

This is from a solution to check if we have a cyclic linkedList or not. Could someone help me understand this line's assignment please (I bolded it in the code snippet below)?

Thank you!

public boolean hasCycle(ListNode head) {
    Set<ListNode> nodesSeen = new HashSet<>();
    while (head != null) {
        if (nodesSeen.contains(head)) {
            return true;
        } else {
            nodesSeen.add(head);
        }
        head = head.next;
    }
    return false;
}
Charlie Armstrong
  • 2,332
  • 3
  • 13
  • 25
  • 4
    It creates a new (and initially empty) `HashSet` with generic parameter `ListNode` (inferred through [type inference](https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html)) and assigns it to a local variable `nodesSeen` of type `Set` with generic parameter `ListNode`. – Turing85 Aug 10 '20 at 17:46
  • Please read [this](https://docs.oracle.com/javase/tutorial/java/concepts/class.html) help page on variable assignment and classes in Java. – Charlie Armstrong Aug 10 '20 at 17:54

0 Answers0