| Java Maps |
|
|
|
| Written by Steve Leonard |
| Saturday, 04 April 2009 11:40 |
|
A few quick tips I have discovered with JAva Maps:
Use ConcurrentHAshMap rather than HashMap for multi-threaded applications Use Collections.checkedMap(new Map(), key.class, value.class) to ensure that you don't add in the wrong type of item. The generics implementation currently allows you to add any old object. The type safe wrapper will cause a classCastException to be thrown. This wrapper class will also ensure that gets are checked too:
import java.util.Collection; import java.util.Collections; import java.util.Map; /** * This wrapper class uses {@link Collections#checkedMap(Map, Class, Class)} to * ensure puts are correct but also checks that gets are the correct class too * @author Steve Leonard * @param * @param
*/ private Map realMap; @Override } /** * This wrapper class uses {@link Collections#checkedMap(Map, Class, Class)} * to ensure puts are correct but also checks that gets are the correct * class too * @param map * @param keyClass * @param valueClass */ public SafeMap(Map map, Class keyClass, Class valueClass) { this.realMap = Collections.checkedMap(map, keyClass, valueClass);
this.keyClass = keyClass; } @Override } /** * this will throw a class cast exception if argument is not the correct * class * @throws ClassCastException */ @Override throw new ClassCastException("Tried to fetch a " + arg0.getClass().getName() + " but key is " } } /** * this will throw a class cast exception if argument is not the correct * class * @throws ClassCastException */ @Override throw new ClassCastException("Tried to fetch a " + arg0.getClass().getName() + " but key is " } } @Override } /** * this will throw a class cast exception if argument is not the correct * class * @throws ClassCastException */ @Override throw new ClassCastException("Tried to fetch a " + arg0.getClass().getName() + " but key is " } } @Override } @Override } /** * this will throw a class cast exception if argument is not the correct * class * @throws ClassCastException */ @Override } /** * this will throw a class cast exception if argument is not the correct * class * @throws ClassCastException */ @Override } @Override } @Override } @Override } } |
| Last Updated on Monday, 08 November 2010 21:10 |