拼合具有自引用列表的列表。拼合具有自引用列表的列表
我有名單列表,其中包括對自身的引用,我需要扁平化這個列表。例如:
例如。我有列表
A = [1,[2,[3]],A,]
扁平列表是這樣的
A = [1,2 ,3]
這是我(在Java中)曾嘗試:
public static void flattenRecurser(List<Integer> result, List<?> nested) {
for (Object item : nested) {
if (item instanceof List<?> && !freq.containsKey((List<?>) item)) {
flattenRecurser(result, (List<?>) item);
} else if (item instanceof Integer) {
result.add((Integer) item);
}
}
}
我打電話flattenRecurser
static Map<List<?>, List<?>> freq = new HashMap<>();
freq.put(nested,nested);
List<Integer> result = new ArrayList<Integer>();
flattenRecurser(result, nested);
前添加嵌套映射稱爲頻率,但我得到一個錯誤,當我把在頻率地圖嵌套列表。
查找嵌套對象的哈希碼導致錯誤。我將如何以不同的方式來解決這個問題,或者有辦法找到嵌套對象的散列。
這裏是我的錯誤:在線程
異常 「主」 java.lang.StackOverflowError的處 java.util中 java.util.ArrayList.iterator(ArrayList.java:834)。 AbstractList.hashCode(AbstractList.java:540)
我沒有行號834或540在我的代碼在所有
你能發佈錯誤嗎?還有你的嵌套對象聲明? – SomeDude
你爲什麼要添加嵌套到地圖?只是比較參考列表A本身,如果它是相同然後繼續前進。 – piyush121
我不能真正包裹我的頭,看看'A = [1,[2,[3]],A]'的扁平列表應該如何顯示。只是'[1,2,3]'或者[1,2,3,1,2,3]',或者如何?你能提供一些例子嗎? –