In the following example how could the instanceof be used with a HashSet?
for (int i = 0; i < empleados.length; i++) {
if (empleados[i] instanceof Comerciante) {
numEmpleados++;
}
}
In the following example how could the instanceof be used with a HashSet?
for (int i = 0; i < empleados.length; i++) {
if (empleados[i] instanceof Comerciante) {
numEmpleados++;
}
}
Assuming that you have objects of type Empleado
in a HashSet
, then you just have to go through it with iterators and apply the same operation on each of them.
HashSet<Empleado> empleados = new HashSet<>();
/* Llenamos la colección con empleados */
// Se recorre la colección
for (Empleado e : empleados) {
if (e instanceof Comerciante)
/* Acción */;
}
This iterator, called forEach
, makes the tour automatically.
We define a variable e
that will refer in each step to an element (in this case used) of the collection.
You can also do it manually, getting an iterator with the method iterator()
of Collection
and handling it explicitly.
Iterator<Empleado> it = empleados.iterator();
Empleado e;
while (it.hasNext()) {
e = it.next();
if (e instanceof Comerciante)
/* Acción */;
}
In this second form, we access the collection element using the next
method of the iterator, checking beforehand that there is a next element that has not yet been processed.