我如何在java中将对象转换为int型?


当前回答

so divide1=me.getValue()/2;

int divide1 = (Integer) me.getValue()/2;

其他回答

对象变量;hastaId

Object hastaId = session.getAttribute("hastaID");

例如,将一个对象转换为int类型,即hasaid

int hastaID=Integer.parseInt(String.valueOf(hastaId));

必须将其强制转换为Integer (int的包装类)。然后,您可以使用Integer的intValue()方法来获取内部整型。

如果你想把字符串对象转换成整数… 你可以简单地传递为:

 int id = Integer.valueOf((String) object_name);

希望这对你有帮助:-)

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

这段代码说明了为什么ArrayList很重要,以及为什么要使用它。简单地从Object转换int。可能会有帮助。

如果对象最初被实例化为Integer,那么可以使用强制转换操作符(子类型)将其向下转换为int。

Object object = new Integer(10);
int i = (Integer) object;

注意,这只适用于至少使用带有自动装箱功能的Java 1.5,否则必须将i声明为Integer,然后对其调用intValue()。

但如果它最初根本不是作为Integer创建的,那么你就不能像这样向下转换。它将导致消息中带有原始类名的ClassCastException。如果通过String#valueOf()获得的对象的toString()表示一个语法上有效的整数(例如,只有数字,如果需要前面有一个负号),那么你可以使用integer #valueOf()或new integer()。

Object object = "10";
int i = Integer.valueOf(String.valueOf(object));

参见:

继承和强制转换教程