commons-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Tim O'Brien" <tobr...@discursive.com>
Subject RE: Modify getter result
Date Tue, 21 Dec 2004 02:38:06 GMT
Stephen already responded, but here is the code you would need:

import org.apache.commons.collections.Factory;
import org.apache.commons.collections.functors.ConstantFactory;
import org.apache.commons.collections.map.LazyMap;
Import java.util.*;

 Map currency = new HashMap()
 {
 	{
 		put("DE", "EUR");
 		put("US", "USD");
 	}
 };

 Factory factory = new ConstantFactory("XY");
 Map lazy = Lazy.map(currency, factory);

 String blah = (String) lazy.get("XY"); 


ConstantFactory is just a factory which returns a constant Object, in
this case a request for "XY" would return the default value.

If you wanted to add your logging code, you could do this instead:

Factory factory = new Factory() {
	public Object create() {
		// logging stuff goes here....
		return "default";
	}
}

But, you should know that after you get "XY", the Map will then contain
"XY" as a key.  If you wanted do this without side-effects (i.e. without
adding a value to the Map), you could mess around with decorating the
original Map with the FixedSizeMap, but the problem here is that adding
a new key will throw IllegalArgumentException.

Tim O'Brien

> -----Original Message-----
> From: Nentwig, Timo [mailto:timo.nentwig@jamba-ag.de] 
> Sent: Monday, December 20, 2004 8:08 AM
> To: commons-user@jakarta.apache.org
> Subject: Modify getter result
> 
> Hi!
> 
> I'm not sure whether this can be done with commons-collections. 
> 
> I need to hook in a collection and return a default value 
> when the requested key does not exist in the collection. E.g.
> 
> Map currency = new HashMap()
> {
> 	{
> 		put("DE", "EUR");
> 		put("US", "USD");
> 	}
> };
> 
> And currency.get("XY") is supposed to return a default value 
> (this may require additional logic and e.g. may write to the 
> logger that an yet unsupported ISOCODE was requested).
> 
> Can this be done?
> 
> Kind regards
> Timo
> 
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: commons-user-unsubscribe@jakarta.apache.org
> For additional commands, e-mail: commons-user-help@jakarta.apache.org
> 
> 
> 

---------------------------------------------------------------------
To unsubscribe, e-mail: commons-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-user-help@jakarta.apache.org


Mime
View raw message