Manu Manu - 6 months ago 12
Java Question

List received like object in a function

This feature may receive in the variable object 2 types of list types:

List<String>
or
List<Integer>
. I have this function:

private void isAList(Object example)
{
}


I can iterate of two ways:


isAList(new ArrayList<String>);


or


isAlist(new ArrayList<Integer>);



I want to know if the first element of this List is a String or an Integer. How I can know which is the first element of this Object (always received a list). this is my code:

private void isAList(Object example)
{
if (example != null && example instanceof List<?> && **FIRST_ELEMENT_OF_example??** instanceof String)
{
for (String cad : (List<String>)example)
{
XXXXXX MY CODE XXXXXX
}
}
}

Answer

Solution:

private void isAList(Object example)
{
    if (example != null && !((List<?>)example).isEmpty() && ((List<?>)example).get(0) instanceof String)
    {
        for (String cad : (List<String>)example)
        {
            // YOUR CODE
        }
    }
}