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?..
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With