, . -, , , (?) 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 ==.