Java - Mixed ArrayLists?

travega picture travega · Jun 10, 2011 · Viewed 22.3k times · Source

Is it possible to store a mixture of object types in an ArrayList? If so how?

This is what I have tried so far:

List<Object> list = new ArrayList<Object>();

list.add(new String("Hello World"));
list.add(new Integer(1));
list.add(new Long(1l));

for (i = 0; i < list.size(); i++) {
    if (list.get(i) instanceof String){
        sqlPreparedStatement.setString((i+1), (String) list.get(i));
    } else if (list.get(i) instanceof Integer) {
        sqlPreparedStatement.setInt((i+1), (Integer) list.get(i));
    } else if (list.get(i) instanceof Long) {
        sqlPreparedStatement.setLong((i+1), (Long) list.get(i));
    }
}

But it throws a casting exception.

Thanks in advance for any input!

Answer

scientiaesthete picture scientiaesthete · Jun 10, 2011

This is what you should have:

List<Object> list = new ArrayList<Object>();

list.add(new String("Hello World"));
list.add(new Integer(1));
list.add(new Long(1l));

for (Object obj: list) {
    if (obj instanceof String){
        sqlPreparedStatement.setString((String) obj);
    } else if (obj instanceof Integer) {
        sqlPreparedStatement.setInt((Integer) obj);
    } else if (obj instanceof Long) {
        sqlPreparedStatement.setLong((Long) obj);
    }
}