這個問題在這里已經有了答案: 在 java 中展平嵌套陣列 8 個答案 3 小時前關閉。
這個問題是在 Razorpay 向我提出的。我想不出解決辦法。任何人都可以幫助我為此撰寫Java代碼。
Object[] array = { 1, 2, new Object[]{ 3, 4, new Object[]{ 5 }, 6, 7 }, 8, 9, 10};
答案應該是:
Integer[] = {1,2,3,4,5,6,7,8,9,10};
即應存盤所有整數元素
我所做的是
for(Object obj: array){
if(obj instanceof Integer) list.add((int)(obj));
}
結果是-> 1,2,8,9,10。如何在串列中添加 3、4、5、6、7?
uj5u.com熱心網友回復:
由于 Object[] 沒有有限的嵌套深度,因此您需要一種遞回方法:
import java.util.ArrayList;
import java.util.List;
public class Answer {
static void extractIntegers(Object[] source, List<Integer> destination) {
for (Object i : source) {
if (i instanceof Object[] array) {
extractIntegers(array, destination);
} else if (i instanceof Integer integer) {
destination.add(integer);
} else {
throw new IllegalArgumentException("Unexpected: " i);
}
}
}
public static void main(String[] args) {
List<Integer> ints = new ArrayList<>();
Object[] array = { 1, 2, new Object[]{ 3, 4, new Object[]{ 5 }, 6, 7 }, 8, 9, 10};
extractIntegers(array, ints);
System.out.println(ints);
}
}
請注意,我正在使用 Java 最近添加的“instanceof 模式匹配”功能。您可以忽略不是Object[]或的物件Integer。我選擇拋出一個例外。
uj5u.com熱心網友回復:
您正在尋找的操作稱為展平陣列。您的輸入是一個陣列,Object其中可以包含Integer或Object[]。所以我們必須在這里處理這兩種情況,并且使用遞回更容易完成:
撰寫一個flatten(Object[] arr)接受Object[]as 引數的函式。該函式將回傳展平List<Integer>后的結果arr。
flatten()遞回函式的邏輯很簡單:
create empty result_array
for each obj in Object[]:
if obj is an Integer:
add obj to the result_array
else obj is Object[]:
flat_obj := flatten(obj)
add all integers of flat_obj into result_array
return result_array
下面是實作上述邏輯的 Java 代碼。希望能幫助到你!
public class Test {
public static List<Integer> flatten(Object[] array) {
List<Integer> result = new ArrayList<>();
for (Object o: array) {
if (o instanceof Object[])
result.addAll( flatten( (Object[]) o) );
else
result.add((Integer) o);
}
return result;
}
public static void main(String[] args) {
Object[] array = { 1, 2, new Object[]{ 3, 4, new Object[]{ 5 }, 6, 7 }, 8, 9, 10};
System.out.println( flatten(array) );
}
}
uj5u.com熱心網友回復:
您只檢查整數,但您的陣列中也有陣列。與instanceof Integer 檢查一起,您還應該添加對instanceof Object[] 的檢查。注意 Object[] 也包含一個 Object[]。因此,您也必須在其中進行相同的檢查。最后你應該有 3 個回圈,每個回圈都會檢查 instanceof Integer 和 instanceof Object[]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/533210.html
標籤:爪哇数组目的遍历
上一篇:使用指標宣告動態長度的字串
