Smooth list of lists that have their own link

Smooth the list of lists that have their own link.

I have a List List that includes a link to myself, and I need to flatten this list.
For example. I have a list

A = [1, [2, [3]], A,]

The smoothed list will look like this

A = [1,2,3]

Here is what I tried (in 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);
        }
    }
}

I add a nested map called freq before calling flattenRecurser

static Map<List<?>, List<?>> freq = new HashMap<>();

freq.put(nested,nested);
List<Integer> result = new ArrayList<Integer>();
flattenRecurser(result, nested);

But I get an error when I put a nested list on a freq map. Detecting a hash code for an embedded object causes an error. How will I address this problem differently or is there a way to find a hash for a nested object.
Here is the error I get:

"main" java.lang.StackOverflowError at java.util.ArrayList.iterator(ArrayList.java:834) java.util.AbstractList.hashCode(AbstractList.java:540)

834 540

+4
2

, . -, , , (?) List.hashCode: List.toString , , List.hashCode . System.identityHashCode.

public static List flatten(List flatten, Set<Integer> ignore) {
    List result = new LinkedList();
    ignore.add(System.identityHashCode(flatten));
    for (Object o : flatten) {
        if (o instanceof List) {
            if (! ignore.contains(System.identityHashCode(o))) {
                result.addAll(flatten((List) o, ignore));
            }
        } else {
            result.add(o);
        }
    }
    return result;
}

:

List C = new ArrayList(Arrays.asList(4, 5, 6));
List B = new ArrayList(Arrays.asList(2, 3, C, 7));
List A = new ArrayList(Arrays.asList(1, B, 8, 9, C));
C.add(C);
B.add(B);
A.add(A);

System.out.println(A);
System.out.println(flatten(A, new HashSet<>()));

:

[1, [2, 3, [4, 5, 6, (this Collection)], 7, (this Collection)], 8, 9, [4, 5, 6, (this Collection)], (this Collection)]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

, , , . . , ignore ==.

+1

. == → .

0

All Articles