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

相关推荐
qq_337763201921 分钟前
国际期货资管系统开发方案|内外盘交易平台源码授权与二次开发支持
java·c语言·开发语言·c++·c#
不定积分要+C_yyy31 分钟前
Java关键字final三种用法、核心特性与高频易错点
java·开发语言
xexpertS2 小时前
队列积压治理:如何避免异步系统出现难以恢复的消息积压
java·开发语言
benchmark_cc9 小时前
如何用 Python + QuantDash 快速构建高胜率“配对交易(Pairs Trading)”策略?
开发语言·人工智能·python·pandas·量化交易·quantdash
阿维的博客日记10 小时前
MultipartFile 是不是表示仅仅是一个分片?
java·后端·spring·multipartfile
程序员无隅10 小时前
Coding Agent 为什么压缩上下文后还能继续工作?上下文模块设计拆解
java·开发语言·数据库
Python+9910 小时前
Java 枚举类(Enum)详解:从基础到高级应用
java·开发语言·python
二炮手亮子11 小时前
浅记java线程池
java·开发语言
一路向北North11 小时前
Spring Security OAuth2.0(23):分布式系统授权-转发明文给微服务
java·spring·微服务
zmzb010311 小时前
C++课后习题训练记录Day157
开发语言·c++