How can I cast an Object to an int in java?
int[] getAdminIDList(String tableName, String attributeName, int value) throws SQLException {
ArrayList list = null;
Statement statement = conn.createStatement();
ResultSet result = statement.executeQuery("SELECT admin_id FROM " + tableName + " WHERE " + attributeName + "='" + value + "'");
while (result.next()) {
list.add(result.getInt(1));
}
statement.close();
int id[] = new int[list.size()];
for (int i = 0; i < id.length; i++) {
try {
id[i] = ((Integer) list.get(i)).intValue();
} catch(NullPointerException ne) {
} catch(ClassCastException ch) {}
}
return id;
}
// enter code here
This code shows why ArrayList
is important and why we use it. Simply casting int
from Object
. May be its helpful.
int i = (Integer) object; //Type is Integer.
int i = Integer.parseInt((String)object); //Type is String.
You have to cast it to an Integer (int's wrapper class). You can then use Integer's intValue() method to obtain the inner int.
Finally, the best implementation for your specification was found.
public int tellMyNumber(Object any) {
return 42;
}
You can't. An int
is not an Object
.
Integer
is an Object
though, but I doubt that's what you mean.
@Deprecated
public static int toInt(Object obj)
{
if (obj instanceof String)
{
return Integer.parseInt((String) obj);
} else if (obj instanceof Number)
{
return ((Number) obj).intValue();
} else
{
String toString = obj.toString();
if (toString.matches("-?\d+"))
{
return Integer.parseInt(toString);
}
throw new IllegalArgumentException("This Object doesn't represent an int");
}
}
As you can see, this isn't a very efficient way of doing it. You simply have to be sure of what kind of object you have. Then convert it to an int the right way.