/**
* A Hashtable that allows duplicate keys.
* It needs to be fleshed out with some constructors for
* actual use. This version is not thread-safe.
* The values you store may not be arrays or ArrayLists.
* To bypass that restriction, you would need private container classes, which
* would get rid of the need for chained instanceofs.
*/
public class HashTableWithDups extends Hashtable
{
/**
* Associate yet another value with a key in a Hashtable that allows duplicates.
* Also use to put the first key/value.
*
* @param key Key to lookup by
* @param value yet another associated value for this key.
*/
public void putDuplicate ( Object key , Object value )
{
Object existing = get( key );
if ( existing == null )
{
put ( key, value );
}
else if ( existing instanceof Object[] )
{
ArrayList a = new ArrayList();
a.addAll ( Arrays.asList( (Object[]) existing ));
a.add ( value );
put ( key, a );
}
else if ( existing instanceof ArrayList )
{
( (ArrayList)existing ).add( value );
}
else
{
put ( key, new Object[] { existing, value } );
}
}
/**
* Get from a Hashtable that allows duplicates
*
* @param key Key to lookup by
* @return array of values associated with this key.
* Note the result is an Object[] array not String[]
* array, even if contents were Strings.
* Null if none found.
* Returns values in same order they were inserted.
*/
public Object[] getDuplicates ( Object key )
{
Object match = get( key );
if ( match == null )
{
return null;
}
else if ( match instanceof Object[] )
{
return (Object[])match;
}
else if ( match instanceof ArrayList )
{
ArrayList a = (ArrayList) match;
return a.toArray ( new Object[a.size()] );
}
else
{
return new Object[] { match };
}
}
}