I have a Hashtable that never contains duplicate values. The problem is that
I in a class only have access to the values of a Hashtable an not the keys.
I would like to be able to removed keys in this Hashtable based on values
and not keys is that possible??
> I have a Hashtable that never contains duplicate values.
> The problem is that in a class only have access to the
> values of a Hashtable an not the keys. I would like to
> be able to removed keys in this Hashtable based on
> values and not keys is that possible??
It is possible to do as [what I think] you require: obtain a Collection
object via the 'values' method, get an Iterator object [via the 'iterator'
method], and remove the underlying key / value entry via the iterator.
Note, however, that you do not have access to the key, and you've
effectively bypassed the 'key handling' methods of the Hashtable. I'm not
sure that this is the best use of a Hashtable, however I realise that this
is a somewhat ad hoc requirement.
The code below provides a quick example.
I hope this helps.
Anthony Borla
// --------------------
import java.util.*;
public class HashTest
{
public static void main(String[] args)
{
Hashtable numbers = new Hashtable();
numbers.put("one", new Integer(1));
numbers.put("two", new Integer(2));
numbers.put("three", new Integer(3));
System.out.println("Size: " + numbers.size());
Iterator nci = numbers.values().iterator();
while (nci.hasNext())
System.out.println(nci.next());
nci = numbers.values().iterator();
while (nci.hasNext())
{
if (((Integer)nci.next()).intValue() == 2)
nci.remove();
}
System.out.println("Size: " + numbers.size());
}
}
bunallo - 26 Feb 2005 11:45 GMT
> > I have a Hashtable that never contains duplicate values.
> > The problem is that in a class only have access to the
[quoted text clipped - 49 lines]
> }
> }
Thank you very much that was just what I needed to do!
"bunallo" wote:
> I have a Hashtable that never contains duplicate values. The problem is that
> I in a class only have access to the values of a Hashtable an not the keys.
> I would like to be able to removed keys in this Hashtable based on values
> and not keys is that possible??
My recommendation: build your own OneToOneMap class which maintains a
key->value hashtable and a value->key hashtable. On average, it'll have
half the performance, but removing-by-value will be (nearly) constant-time.
Cheers, Paul