我如何在java中将对象转换为int型?
当前回答
必须将其强制转换为Integer (int的包装类)。然后,您可以使用Integer的intValue()方法来获取内部整型。
其他回答
答:
int i = ( Integer ) yourObject;
如果你的对象已经是一个整数,它将顺利运行。即:
Object yourObject = 1;
// cast here
or
Object yourObject = new Integer(1);
// cast here
etc.
如果你的对象是其他类型的对象,你需要先将它(如果可能的话)转换为int类型:
String s = "1";
Object yourObject = Integer.parseInt(s);
// cast here
Or
String s = "1";
Object yourObject = Integer.valueOf( s );
// cast here
参考代码:
public class sample
{
public static void main(String[] args)
{
Object obj=new Object();
int a=10,b=0;
obj=a;
b=(int)obj;
System.out.println("Object="+obj+"\nB="+b);
}
}
必须将其强制转换为Integer (int的包装类)。然后,您可以使用Integer的intValue()方法来获取内部整型。
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。可能会有帮助。
不可能做到。int不是一个对象,它是一个基本类型。你可以将它转换为Integer,然后获取int。
Integer i = (Integer) o; // throws ClassCastException if o.getClass() != Integer.class
int num = i; //Java 1.5 or higher
推荐文章
- 在maven中安装mvn到底做什么
- 不可变与不可修改的集合
- 如何在JSON中使用杰克逊更改字段名
- GSON -日期格式
- 如何从线程捕获异常
- 无法解析主机"<URL here>"没有与主机名关联的地址
- 如何在Java中打印二叉树图?
- String.format()在Java中格式化双重格式
- 字符串不能识别为有效的日期时间“格式dd/MM/yyyy”
- com.jcraft.jsch.JSchException: UnknownHostKey
- Java中的操作符重载
- 如何加速gwt编译器?
- 在Hibernate中重新连接分离对象的正确方法是什么?
- 应该……接住环内还是环外?
- 在JavaScript中根据键值查找和删除数组中的对象