Search This Blog

Breaking

Wednesday, 5 August 2020

Find Integer from different objects

This was a question asked to me in one of my automation interviews. I liked this question. It was a little bit different than the traditional ones. 

So the question was :

We have some values with us. You need to find out the integer values from those values. 

Example : 1, a, 0.1 , "dsds", -1
The output should be 1 and -1



You are free to use any language.

I tried to do it with Java. 

So to implement it, first, I thought to put all these input values into a list. 
But what should be the type of list here? (That's why I liked this question) 

As it's all of the different types, so I created an ArrayList of the object type.

ArrayList<Object> list = new ArrayList();

Now, I need to add these values to this ArrayList.
So I used the add method and added all values to this list.

list.add(1);
list.add('a');
list.add(0.1);
list.add("dsds");
list.add(-1);

Now I created another list to hold all the integer values. 

ArrayList list1 = new ArrayList(list.size());

Now, I used the instanceOf method present in object class to check the type of the value preent inside
list.

for(int i = 0; i < list.size(); i++)
{
    if (list.get(i) instanceof Integer) {
        list1.add(list.get(i));
    }

}
In the end, I printed the new list;
System.out.println("New list" + list1); // [1, -1]

No comments:

Post a Comment