You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

KeyMapper.java 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. @VaadinApache2LicenseForJavaFiles@
  3. */
  4. package com.vaadin.terminal;
  5. import java.io.Serializable;
  6. import java.util.Hashtable;
  7. /**
  8. * <code>KeyMapper</code> is the simple two-way map for generating textual keys
  9. * for objects and retrieving the objects later with the key.
  10. *
  11. * @author Vaadin Ltd.
  12. * @version
  13. * @VERSION@
  14. * @since 3.0
  15. */
  16. @SuppressWarnings("serial")
  17. public class KeyMapper implements Serializable {
  18. private int lastKey = 0;
  19. private final Hashtable<Object, String> objectKeyMap = new Hashtable<Object, String>();
  20. private final Hashtable<String, Object> keyObjectMap = new Hashtable<String, Object>();
  21. /**
  22. * Gets key for an object.
  23. *
  24. * @param o
  25. * the object.
  26. */
  27. public String key(Object o) {
  28. if (o == null) {
  29. return "null";
  30. }
  31. // If the object is already mapped, use existing key
  32. String key = objectKeyMap.get(o);
  33. if (key != null) {
  34. return key;
  35. }
  36. // If the object is not yet mapped, map it
  37. key = String.valueOf(++lastKey);
  38. objectKeyMap.put(o, key);
  39. keyObjectMap.put(key, o);
  40. return key;
  41. }
  42. /**
  43. * Retrieves object with the key.
  44. *
  45. * @param key
  46. * the name with the desired value.
  47. * @return the object with the key.
  48. */
  49. public Object get(String key) {
  50. return keyObjectMap.get(key);
  51. }
  52. /**
  53. * Removes object from the mapper.
  54. *
  55. * @param removeobj
  56. * the object to be removed.
  57. */
  58. public void remove(Object removeobj) {
  59. final String key = objectKeyMap.get(removeobj);
  60. if (key != null) {
  61. objectKeyMap.remove(removeobj);
  62. keyObjectMap.remove(key);
  63. }
  64. }
  65. /**
  66. * Removes all objects from the mapper.
  67. */
  68. public void removeAll() {
  69. objectKeyMap.clear();
  70. keyObjectMap.clear();
  71. }
  72. }