[英]Convert long array to int array in Java
我剛開始使用 java,我無法將 long 數組類型轉換為 int 數組。 你能給我一個建議我該怎么做嗎? 謝謝!
public class Main {
public static void main(String[] args) {
long[] numbers;
numbers = sorting(new long[]{5, 21, 19, 55, 94, 73, 69, 100,});
}
public static long[] sorting(long [] numbers) {
for (long num : numbers) {
long j = 0;
for (int i = 0; i < numbers.length - 1; i++) {
if (numbers[i] > numbers[i + 1]) {
j = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = j;
}
}
System.out.println(num + ",");
}
return (numbers);
要將 long[] 轉換為 int[],您需要遍歷 long[] 數組,將每個單獨的數字轉換為 int 並將其放入 int[] 數組。
// Your result
long[] numbers = sorting(new long[] {5, 21, 19, 55, 94, 73, 69, 100});
// Define a new int array with the same length of your result array
int[] intNumbers = new int[numbers.length];
// Loop through all the result numbers
for(int i = 0; i < numbers.length; i++)
{
// Cast to int and put it to the int array
intNumbers[i] = (int) numbers[i];
}
或者您也可以使用 Java Streams (>= 1.8) 作為較短的版本:
int[] intArray = Arrays.stream(numbers).mapToInt(i -> (int) i).toArray();
在convert-an-int-array-to-long-array-using-java-8中也有類似的問題
你可以試試這個:
long[] longArray = {1, 2, 3};
int[] intArray = Arrays.stream(longArray).mapToInt(i -> (int) i).toArray();
這里還有一點要說。 如果您只是將long
類型轉換為int
,您將面臨整數溢出的風險。 所以為了安全起見,我建議使用Math#toIntExact
函數來確保轉換是安全的。 這是一個例子:
long[] longs = new long[] {1,2,3,4,5};
int[] ints = Arrays.stream(longs).mapToInt(Math::toIntExact).toArray();
如果longs
包含無法轉換為int
的值,則將拋出ArithmeticException
,例如
long[] longs = new long[] {1,2,3,4,5, Long.MAX_VALUE};
int[] ints = Arrays.stream(longs).mapToInt(Math::toIntExact).toArray(); // Throws here
將Exception in thread "main" java.lang.ArithmeticException: integer overflow
這確保您的代碼正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.