In this Java program, we are dealing with a problem where we have an ArrayList that contains both integers and strings. The task is to traverse through the list using a Java Iterator until we encounter a string. The iterator should stop at the first occurrence of a string.
CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷
The solution approach is to use the Java Iterator's hasNext() and next() methods to traverse through the ArrayList. Inside the while loop, we check if the current element is an instance of String using the 'instanceof' operator. If it is, we break the loop, thus stopping the iteration at the first occurrence of a string. The main method populates the ArrayList with integers and strings, then calls the func method passing the ArrayList. The returned iterator is then used to print the remaining elements of the ArrayList, which are all strings.
/**
*
*/
package com.javaaid.hackerrank.solutions.languages.java.oop;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
/**
*
*/
public class JavaIterator {
static Iterator func(ArrayList mylist) {
Iterator it = mylist.iterator();
while (it.hasNext()) {
Object element = it.next();
if (element instanceof String)// Hints: use instanceof operator
break;
}
return it;
}
@SuppressWarnings({ "unchecked" })
public static void main(String[] args) {
ArrayList mylist = new ArrayList();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
for (int i = 0; i < n; i++) {
mylist.add(sc.nextInt());
}
mylist.add("###");
for (int i = 0; i < m; i++) {
mylist.add(sc.next());
}
Iterator it = func(mylist);
while (it.hasNext()) {
Object element = it.next();
System.out.println((String) element);
}
sc.close();
}
}
If you have a HackerRank coding test coming up, you can use CodeRankGPT to your advantage. It will assist you during your interview and help ensure you get the job.
AI is here now, and other candidates might be using it to get ahead and win the job. 🧐
The form has been successfully submitted.