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

允我心安 提交于 2020-01-13 12:02:50

问题


i know how to hard code an algorithm on how to check the types of each object in an arraylist, but is there any other way in checking the type of that ArrayList<> in one go, i mean my application has only three types of arraylist. Say i have a function that returns an ArrayList, and its definiton is that in a variable o (its an arraylist of object ofcourse) i'll add a person object,

o.add(person);

and having added all person data on an arraylist of objects and when a call this function say the name of my function is getData(),

ArrayList <Object> obj = getData();

so i know that in that ArrayList that i returned from calling getData() that it is all person object, how do i know the type of that ArrayList?.

Just wanted that function to be more generic in sense, this is for my application though, geniric troughout my application.

Is there any other way of doing this, i can think of an algorithm but is there any short cut or easy way of doing this?..


回答1:


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.




回答2:


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);



回答3:


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

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


来源:https://stackoverflow.com/questions/12320429/java-how-to-check-the-type-of-an-arraylist-as-a-whole

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!