Integer.valueOf()
时间: 2023-06-22 21:46:07 浏览: 68
`Integer.valueOf()` 方法是一个工厂方法,用于返回一个表示指定 `int` 值的 `Integer` 对象。该方法有两个重载:
1. `public static Integer valueOf(int i)`:返回一个表示指定 `int` 值的 `Integer` 对象。
2. `public static Integer valueOf(String s)`:返回一个保存指定的字符串所表示的值的 `Integer` 对象。
与 `new Integer()` 构造方法不同的是,`Integer.valueOf()` 方法返回的是一个 `Integer` 类型的缓存对象,而不是每次都创建一个新的对象。在范围为 `-128` 到 `127` 的整数值之间,`Integer.valueOf()` 方法返回的是缓存中的对象,超出这个范围的整数值每次都会创建新的对象。这样可以提高性能和节省内存。
例如,下面的代码演示了使用 `Integer.valueOf()` 方法创建 `Integer` 对象的方法:
```java
Integer a = Integer.valueOf(100);
Integer b = Integer.valueOf("200");
```
上面的代码会创建两个 `Integer` 对象,一个表示整数值 `100`,另一个表示整数值 `200`。由于这两个整数值都在缓存范围内,因此 `valueOf()` 方法返回的是缓存中的对象,而不是每次都创建一个新的对象。
相关问题
integer.valueof
Integer.valueOf(String str)方法也可以将String类型转换为Integer类型,例如:
```
String str = "123";
Integer num = Integer.valueOf(str); // num的值为123
```
与parseInt()方法不同的是,valueOf()方法返回的是一个Integer对象,而parseInt()方法返回的是int类型的值。同时,如果String类型无法转换为Integer类型,valueOf()方法会返回null,而不是抛出异常。
Integer.valueOf
Integer.valueOf(String str)方法也可以将String类型转换为Integer类型,例如:
```
String str = "123";
Integer num = Integer.valueOf(str); // num的值为123
```
与parseInt()方法不同的是,valueOf()方法返回的是一个Integer对象,而parseInt()方法返回的是int类型的值。同时,如果String类型无法转换为Integer类型,valueOf()方法会返回null,而不是抛出异常。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)