How do I find out what type each object is in a ArrayList<Object>?
In C#:
Fixed with recommendation from Mike
ArrayList list = ...;
// List<object> list = ...;
foreach (object o in list) {
if (o is int) {
HandleInt((int)o);
}
else if (o is string) {
HandleString((string)o);
}
...
}
In Java:
ArrayList<Object> list = ...;
for (Object o : list) {
if (o instanceof Integer)) {
handleInt((Integer o).intValue());
}
else if (o instanceof String)) {
handleString((String)o);
}
...
}
You can use the getClass()
method, or you can use instanceof. For example
for (Object obj : list) {
if (obj instanceof String) {
...
}
}
or
for (Object obj : list) {
if (obj.getClass().equals(String.class)) {
...
}
}
Note that instanceof will match subclasses. For instance, of C
is a subclass of A
, then the following will be true:
C c = new C();
assert c instanceof A;
However, the following will be false:
C c = new C();
assert !c.getClass().equals(A.class)
for (Object object : list) {
System.out.println(object.getClass().getName());
}
You almost never want you use something like:
Object o = ...
if (o.getClass().equals(Foo.class)) {
...
}
because you aren't accounting for possible subclasses. You really want to use Class#isAssignableFrom:
Object o = ...
if (Foo.class.isAssignableFrom(o)) {
...
}