java: how to check the type of an ArrayList as a whole

There is no such thing as 'the type' of an ArrayList.

The class ArrayList stores a list of Object references. It doesn't know and doesn't care if they are all of some type.

The Java generic system adds compile-time checking to help you keep track of types. So, if you declare ArrayList<Person>, you will get compile errors if you write code that could insert a non-Person into your list.

At runtime, the only way to tell what is in an ArrayList to iterate over all the contained items and check them with instanceof.


Actually there is a way without casting every item manually(it still is ugly though..)

//start with an arraylist of unknown generic type
ArrayList <Object> obj = getData();

//Make an array from it(basically the same as looping over the list
// and casting it to the real type of the list entries)
Object[] objArr = obj.toArray();

//Check if the array is not empty and if the componentType of the 
//array can hold an instance of the class Person 
if(objArr.length>0 
    && objArr.getClass().getComponentType().isAssignableFrom(Person.class)) {
    // do sth....
}

This should not give any unchecked warnings.

You could use it like this:

private boolean isArrayOfType(Object[] array,Class<?> aClass) {
    return array.length > 0
            && array.getClass().getComponentType().isAssignableFrom(aClass);
}
Object[] personArr = getData().toArray();
if(isArrayOfType(personArr,Person.class) {
   //Do anything...

}

What won't work is the following:

// -> This won't work, sry!
       ArrayList<Person> personArrayList = Arrays.asList((Person[])personArr);

If the list is not empty, get the first element:

type = this.list.get(0).getClass().getSimpleName();

Tags:

Java

Arraylist