将Object转换为原始int

时间:2010-04-02 06:49:03

标签: java

如何将对象(非字符串)(如TreeNode.item)转换为类似int的原语。

2 个答案:

答案 0 :(得分:6)

回复你的上一条评论:只需仔细检查,该对象实际上是Integer类型,然后使用自动装箱(我假设您的编译器级别为1.5 +):

Object o = getTheValue();
int result = 0; // we have to initialize it here!
if (o instanceof Integer) {
  result = (Integer) o;
} else {
  throw new WTFThisShouldHaveBeenIntegerException();
}

答案 1 :(得分:0)

hashCode()可能就是你想要的。然后,它可能不会。

相关问题