在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值等特殊情况下,才需要考虑其他方法。

相关推荐
BD_Marathon10 小时前
SpringBoot——多环境开发配置
java·spring boot·后端
代码N年归来仍是新手村成员10 小时前
【Java转Go】即时通信系统代码分析(一)基础Server 构建
java·开发语言·golang
Z1Jxxx10 小时前
01序列01序列
开发语言·c++·算法
沐知全栈开发11 小时前
C语言中的强制类型转换
开发语言
关于不上作者榜就原神启动那件事11 小时前
Java中大量数据Excel导入导出的实现方案
java·开发语言·excel
坚定学代码11 小时前
基于观察者模式的ISO C++信号槽实现
开发语言·c++·观察者模式·ai
Wang's Blog11 小时前
Nodejs-HardCore: Buffer操作、Base64编码与zlib压缩实战
开发语言·nodejs
Coder_Boy_11 小时前
基于SpringAI的在线考试系统设计总案-知识点管理模块详细设计
android·java·javascript
csbysj202011 小时前
C# 集合(Collection)
开发语言
Assby12 小时前
如何尽可能精确计算线程池执行 shutdown() 后的耗时?
java·后端