java Long数组 转 Integer 数组
时间: 2024-06-13 19:08:08 浏览: 17
可以使用Java中的循环和类型转换来将Long数组转换为Integer数组。下面是一个示例代码:
```java
Long[] longArray = {1L,2L, 3L};
Integer[] intArray = new Integer[longArray.length];
for (int i = 0; i < longArray.length; i++) {
intArray[i] = longArray[i].intValue();
}
```
在上面的代码中,我们首先定义了一个Long类型的数组longArray,然后定义了一个与其长度相同的Integer类型的数组intArray。接下来,我们使用for循环遍历longArray数组,并将每个元素转换为Integer类型并存储在intArray数组中。
相关问题
java long 转int数组
你可以使用以下代码将一个 long 类型的数值转换为 int 数组:
```java
long number = 1234567890L; // 要转换的 long 数值
int[] array = new int[Long.SIZE / Integer.SIZE]; // 创建 int 数组
for (int i = 0; i < array.length; i++) {
array[i] = (int) (number >> (i * Integer.SIZE));
}
```
在上述代码中,我们首先声明一个 long 类型的变量 `number`,它是要转换的数值。然后,我们创建一个 int 数组 `array`,该数组的长度为 `Long.SIZE / Integer.SIZE`,这是因为 long 类型的大小是 int 类型的大小的两倍。
接下来,我们使用一个循环,将 long 数值逐个转换为 int,并存储到数组中。在每次迭代中,我们使用右移运算符 `>>` 将 long 数值按位右移 `i * Integer.SIZE` 位,然后将结果强制转换为 int 类型并赋值给数组元素。
请注意,由于 long 类型的大小超过了 int 类型的范围,因此可能会丢失一些信息。因此,在进行转换时,请确保 long 数值不超过 int 类型的表示范围。
java数组数据类型转换
Java数据类型的转换可以分为基本数据类型数组转引用数据类型数组和引用数据类型数组转基本数据类型数组两种情况。
1. 基本数据类型数组转引用数据类型数组:
- 使用stream()方法可以将int[], double[], long[]等基本数据类型数组转换为相应的引用类型数组,例如:
```
List<Integer> a = new ArrayList<>();
a.add(1);
a.add(2);
int[] arr = a.stream().mapToInt(Integer::valueOf).toArray();
```
- 使用boxed()方法和toArray()方法可以将除了char[]的数组转换为相应的引用类型数组,例如:
```
int[] obj2 = {4, 5, 6};
Integer[] newObj = Arrays.stream(obj2).boxed().toArray(Integer[]::new); ```
2. 引用数据类型数组转基本数据类型数组:
- 使用stream()方法和mapToInt()方法可以将Integer[], Double[], Long[]等引用类型数组转换为相应的基本数据类型数组,例如:
```
Integer[] arr = {1, 2, 3};
int[] newArr = Arrays.stream(arr).mapToInt(Integer::intValue).toArray();
```
- 使用IntStream.of()方法和toArray()方法可以将Integer[], Double[], Long[]等引用类型数组转换为相应的基本数据类型数组,例如:
```
Integer[] arr = {1, 2, 3};
int[] newArr = IntStream.of(arr).toArray();
```
相关推荐
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)