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

相关推荐
lly2024067 小时前
Bootstrap 警告框
开发语言
2601_949146537 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
曹牧7 小时前
Spring Boot:如何测试Java Controller中的POST请求?
java·开发语言
KYGALYX7 小时前
服务异步通信
开发语言·后端·微服务·ruby
zmzb01038 小时前
C++课后习题训练记录Day98
开发语言·c++
爬山算法8 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
kfyty7258 小时前
集成 spring-ai 2.x 实践中遇到的一些问题及解决方案
java·人工智能·spring-ai
猫头虎8 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
李少兄8 小时前
在 IntelliJ IDEA 中修改 Git 远程仓库地址
java·git·intellij-idea
YUJIANYUE9 小时前
PHP纹路验证码
开发语言·php