-2

I'm solving this problem in Hackerrank. How can i use instanceof operator in Java to successfully compile the code?

Link : https://www.hackerrank.com/challenges/java-iterator

The incomplete code :

import java.util.*;
public class Main
{
static Iterator func(ArrayList mylist)
{
  Iterator it=mylist.iterator();
  while(it.hasNext())
  {
     Object element = it.next();
     if(~~Complete this line~~)//Hints: use instanceof operator
        break;
  }
  return it;

}

public static void main(String []argh)
{
  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);
  }

 }
}

Even though i got it done by using if(element == "###"), please guide me on how to use instanceof operator at that place.

Edit : That thread couldn't provide answers as to how to use that instanceof operator to check for the instance of a special character group like "###" in a ArrayList. Please help me understand. Sorry if I'm violating any rule here.

Swaggerboy
  • 339
  • 1
  • 2
  • 15
  • Sorry, But i had gone through that thread earlier and couldn't understand how to use instanceof operator in my problem. Can you please help? – Swaggerboy May 15 '16 at 12:35

3 Answers3

2

This code is adding Integer instances followed by String instances to the same ArrayList.

Though you didn't say so, it seems the goal of func is to return an Iterator that points to the first String element following the "###" element. Therefore func should iterate over the elements of the ArrayList until it encounters a String instance, which would be the "###" String.

static Iterator func(ArrayList mylist)
{
  Iterator it=mylist.iterator();
  while(it.hasNext())
  {
     Object element = it.next();
     if(element instanceof String)
        break;
  }
  return it;

}
Eran
  • 387,369
  • 54
  • 702
  • 768
1

Ex of instanceof operator-- import java.util.Enumeration; import java.util.Vector;

public class VecReplace {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Vector vector=new Vector();

        vector.add(0, 10);
        vector.add(1, "xyz");
        vector.add(2, 30);
        vector.add(3, 40);
        System.out.println(vector);

        vector.set(3, "abc");
        System.out.println(vector);

        Enumeration e=vector.elements();
        while(e.hasMoreElements())
        {
            Object o=e.nextElement();
            if(o instanceof Integer)
            {
                Integer i=(Integer) o;

                System.out.println(i);
            }

        }


}

}

1
if(element instanceof String){

....... } This should give you the expected output.

Pragin M
  • 58
  • 2
  • 10