java 将 Object 转换为原始 int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2565397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 21:49:14  来源:igfitidea点击:

Convert Object into primitive int

java

提问by alan

How to Convert an Object(not String),like TreeNode.item, into primitive like int.

如何将一个对象(不是字符串),比如 TreeNode.item,转换成像 int 这样的原始类型。

回答by Andreas Dolk

In response to your last comment: just double-check, that the object is really of type Integer, then use auto-boxing (I assume that your compiler level is 1.5+):

回应您的最后一条评论:只需仔细检查,该对象确实是 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();
}

回答by Daniel Earwicker

hashCode()might be what you want. Then again, it might not.

hashCode()可能是你想要的。再说一次,它可能不会。