在Java中,将`Short`(包装类)或`short`(基本类型)转换为`int`

在Java中,将Short(包装类)或short(基本类型)转换为int有以下几种常用方法:

1. 自动拆箱 + 自动类型提升(最常用)

java 复制代码
Short shortObj = 100;
short shortPrimitive = 200;

// 自动拆箱 + 自动类型提升
int intValue1 = shortObj;        // Short → int
int intValue2 = shortPrimitive;  // short → int

2. 显式调用方法

java 复制代码
Short shortObj = 100;
short shortPrimitive = 200;

// 使用intValue()方法
int intValue1 = shortObj.intValue();

// 使用强制类型转换(实际上不需要,因为short可以自动提升为int)
int intValue2 = (int) shortPrimitive;

3. 处理可能为null的情况

java 复制代码
Short shortObj = null;

// 方法1:使用三元运算符
int intValue1 = shortObj != null ? shortObj : 0;

// 方法2:使用Optional
int intValue2 = Optional.ofNullable(shortObj).orElse((short)0).intValue();

// 方法3:使用Objects.requireNonNullElse(Java 9+)
int intValue3 = Objects.requireNonNullElse(shortObj, (short)0);

4. 字符串转换场景

java 复制代码
String str = "123";
Short shortObj = Short.parseShort(str);  // 先转成Short
int intValue = shortObj.intValue();      // 再转成int

// 或者直接
int intValue = Integer.parseInt(str);    // 直接转成int

推荐做法

日常开发中最推荐使用第一种方法(自动拆箱 + 自动类型提升),因为:

  • 代码简洁
  • 性能良好
  • 可读性强

只有在需要处理null值等特殊情况下,才需要考虑其他方法。

相关推荐
敲上瘾12 分钟前
Qt控件通用属性:geometry、qrc资源到QSS样式表等
开发语言·c++·qt·ui
听情歌落俗1 小时前
嵌入式学习1-C语言基础语法与STM32实践
c语言·开发语言
小飞在努力2 小时前
【实现负载均匀在线判题⑤】MVC 架构搭建与 Model 题目数据模块实现
c语言·开发语言·c++·笔记·后端
落羽的落羽3 小时前
【C++】现代容器: tuple、optional、variant、any、string_view
linux·开发语言·数据结构·c++·人工智能·计算机网络·算法
会编程的吕洞宾4 小时前
Spring AI 2.0 工具调用实战:让 AI 自动调用你的 Java 方法
java·人工智能·经验分享·后端·spring
斯维赤4 小时前
SELECT * 为什么是覆盖索引的天敌?
java·后端·mysql
stormsha4 小时前
库存 5,10 个并发各买 1 件:为什么最后不剩 -5 件
java·数据库·mysql
小飞在努力5 小时前
【实现负载均匀在线判题④】接入 cpp-httplib 实现编译服务 HTTP 网络化
c语言·开发语言·c++·笔记·http
RobinXYuan5 小时前
【Java 字节码探秘】02 ClassFile 骨架:十个字段
java·jvm·源码阅读
炸薯条!5 小时前
Python面向对象基础:类与对象、实例方法、魔法方法和属性详解
java·开发语言·python