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
ArrayListstores a list ofObjectreferences. 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-Personinto your list.At runtime, the only way to tell what is in an
ArrayListto iterate over all the contained items and check them withinstanceof.