Iterators, sorting, equals and hashCode, step by step

Debt 1

Iterators and for-each

ConcurrentModificationException

Debt 2

Sorting your own objects

Comparable Β· Comparator

Debt 3

Duplicates in a HashSet

equals Β· hashCode

Collections ask your objects questions

If they answer wrongly, everything fails silently

for-each

for (String n : nombres)

Iterator

it = nombres.iterator() while (it.hasNext()) { it.next() }

Just three methods

hasNext() next() remove() Iterable β†’ iterator()

The same syntax, very different structures

ArrayListHashSetArrayDequeLinkedListTreeSet

Deleting inside the for-each

tareas.remove(t)

The list changes behind the iterator β†’ ConcurrentModificationException

Option 1 Β· explicit iterator

it.remove()

Deletes AND keeps the iterator consistent

Option 2 Β· since Java 8

tareas.removeIf(t -> …)

One line, no explicit iterator

Nothing to do with threads

It happens the same in a single-threaded program

Compile error

Collections.sort(libros)

Libro does not implement Comparable: sort by title, author, pages?

negative

a goes BEFORE b

zero

they are equivalent

positive

a goes AFTER b

The classic trap

return this.edad - otro.edad;

With large values it overflows the int and the sign is wrong. Use Integer.compare.

Comparable

compareTo(Libro otro)

Natural order INSIDE the class: only one per class

Comparator

Comparator.comparing(…)

Orders OUTSIDE the class: as many as you need

Chaining criteria

comparing(…).thenComparing(…) comparingInt(…).reversed()

With nulls

nullsLast(naturalOrder())

Without the sort blowing up

Reflexive

a.equals(a) β†’ true

Symmetric

a.equals(b) β‡’ b.equals(a)

Transitive

a=b and b=c β‡’ a=c

Consistent

Same result if nothing changed

Against null

a.equals(null) β†’ false

Overload vs override

equals(Libro o) β‰  equals(Object o)

Collections call equals(Object)

The rule

a.equals(b) β‡’ a.hashCode() == b.hashCode()

The reverse is not required

Two different objects may share a hash: a collision, and it is normal

The same fields

Objects.hash(titulo, autor, paginas)

record

record Libro(String titulo, String autor, int paginas)

Correct equals, hashCode and toString, generated by the compiler

equals without hashCodeequals(Libro o) instead of equals(Object o)compareTo returning a - b== to compare StringMutating an object stored in a HashSetremove inside a for-eachcompareTo inconsistent with equals

1 Step

Immutable Libro

titulo Β· autor Β· paginas

2 Step

equals + hashCode

Over the three fields

3 Step

Comparable

Natural order by title

4 Step

HashSet

Discards the duplicate

5 Step

Comparator

Three different orders

6 Step

TreeSet

The compareTo trap

Consistency

compareTo returns 0 exactly when equals returns true

1 Β· for-each = Iterator2 Β· CME is not about threads3 Β· removeIf Β· it.remove()4 Β· Comparable vs Comparator5 Β· compareTo: only the sign6 Β· equals + hashCode together7 Β· equals(Object o)8 Β· TreeSet decides with compareTo9 Β· record gives it for free

CursoDeJava Β· l16_iteradores_ordenamiento_equals_hashcode

Iterators, lambdas, method references and three integrators