when should we use hasnext()

sohan_snow
Tera Contributor

Hi All,

I understand that hasnext() will either return true or false, but next() also in a way does the same thing and then goes to the next record.

I would like understand when should we use hasnext(), Is there any case scenario where usage of hasnext() is important

Thanks in advance

1 ACCEPTED SOLUTION

Dave Smith1
ServiceNow Employee
ServiceNow Employee

Although the question has been answered, you may find reading up about an iterator explains a bit about the underlying purpose of these two methods.



Suggested reading: https://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html



For what it's worth, consider standing near the edge of a cliff:


  • hasNext() is usually used to check there's another step to be taken
  • next() takes that step.

View solution in original post

11 REPLIES 11

sbrnag
Mega Expert

Let's say you want to know whether any results there for search criteria instead of getting the next object just use hasNext() if it returns true it means there is at least one result for your search criteria.



So fast not need to get the full object.


Gowrisankar Sat
Tera Guru

hasnext() should be used when you need to check if there are any records after you execute a query. If will stop after it finds a record and returns true/false.



next() should be used to iterate loop of records, it will execute until all records are iterated.It will return objects of records.


Harsh Vardhan
Giga Patron

Hi Sohan,



please check the link below. same concept we have in service-now because it's developed on java



Differnce between next() and hasNext() in java collections - Stack Overflow