How to determine if List contains in Java

From Java Documentation :

Note. Despite the fact that lists must contain elements as elements, it is recommended to take special care: the equals and hashCode methods are no longer defined in such a list.

The problem is that the hash code of the List object is computed recursively.

 int hashCode = 1;
 for (E e : list)
     hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());

The question is how to make my code an idiotic proof and determine if the List object (or some of its elements or even deeper) contains the List object itself.

How to save a list of List objects when traversing a List object and be able to call the contains () method? Does System.identityHashCode (object) support and testing against it is good enough?

+4
source share
1

System.identityHashCode , - IdentityHashMap.

boolean containsCircularReference(Iterable<?> iterable) {
  return containsCircularReference(
     iterable,
     Collections.newSetFromMap(new IdentityHashMap<Object, Boolean>()));
}

private boolean containsCircularReference(Object o, Set<Object> seen) {
  if (seen.contains(o)) {
    return true;
  }
  seen.add(o);
  if (o instanceof Iterable) {
    for (Object o2 : (Iterable<?>) o) {
      if (containsCircularReference(o2, seen)) {
        return true;
      }
    }
  }
  return false;
}

System.identityHashCode . 2 ^ 32 JVM, 2 ^ 32 identityHashCode...

Iterable, , , . , equals hashCode ; , equals hashCode , .

+4

All Articles