What is the difference between hasNext() and next()?



  • What is the difference between hasNext() and next() and where it is used? Is it used in Selenium WebDriver or Selenium IDE.



  • I think Kannathasan has explained the difference perfectly, but I'd like to add some context:

    Making the assumption that you're using Java, they're part of the Iterator interface as described here: https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html

    This interface is a part of Java. While it has nothing to do with Selenium-Webdriver, parts of Selenium-Webdriver may implement it.

    From the documentation:

    hasNext()

    boolean hasNext()
    
    Returns true if the iteration has more elements. (In other words, returns true if next() would return an element rather than throwing an exception.)
    
    Returns:
        true if the iteration has more elements 
    

    next()

    E next()
    
    Returns the next element in the iteration.
    
    Returns:
        the next element in the iteration
    Throws:
        NoSuchElementException - if the iteration has no more elements
    

    I can't think of a place in Selenium-Webdriver where I've used an iterator directly, but it's implemented in a few places where you could use it if you really wanted to.

    If you have an ArrayList for example, you can access and use the Iterator instead of using a for loop. There may be times where this is advantageous, but I can't think of any immediate examples.

    Take this simple use with an ArrayList

     List <String> strings = new ArrayList <String>();
    
     strings.add("Example 1");
     strings.add("Example 2");
    
     Iterator<String> iterator = strings.iterator();
    
     while (iterator.hasNext()) {
      System.out.println(iterator.next());
     }
    

    While there are still items in the list to go through, it will print them out. As there are 2 items in the list, it will run through 2 iterations and print out both strings that were added.


Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2