1 package org.exolab.castor.mapping.loader.collection.handler; 2 3 import java.util.Enumeration; 4 import java.util.SortedMap; 5 import java.util.TreeMap; 6 7 import org.exolab.castor.mapping.CollectionHandler; 8 import org.exolab.castor.mapping.MapItem; 9 import org.exolab.castor.mapping.loader.CollectionHandlers; 10 import org.exolab.castor.mapping.loader.J2CollectionHandlers.IteratorEnumerator; 11 12 public final class SortedMapCollectionHandler<T> implements CollectionHandler<T> { 13 14 @SuppressWarnings("unchecked") 15 public Object add(Object collection, T object) { 16 17 T key = object; 18 T value = object; 19 20 if (object instanceof MapItem) { 21 MapItem<T, T> item = (MapItem<T, T>) object; 22 key = item.getKey(); 23 value = item.getValue(); 24 if (value == null) { 25 value = object; 26 } 27 if (key == null) { 28 key = value; 29 } 30 } 31 32 if (collection == null) { 33 collection = new TreeMap<T, T>(); 34 ((SortedMap<T, T>) collection).put(key, value); 35 return collection; 36 } 37 ((SortedMap<T, T>) collection).put(key, value); 38 return null; 39 } 40 41 @SuppressWarnings("unchecked") 42 public Enumeration<T> elements(final Object collection) { 43 if (collection == null) 44 return new CollectionHandlers.EmptyEnumerator<T>(); 45 return new IteratorEnumerator<T>(((SortedMap<T, T>) collection).values().iterator()); 46 } 47 48 @SuppressWarnings("unchecked") 49 public int size(final Object collection) { 50 if (collection == null) 51 return 0; 52 return ((SortedMap<T, T>) collection).size(); 53 } 54 55 @SuppressWarnings("unchecked") 56 public Object clear(final Object collection) { 57 if (collection != null) 58 ((SortedMap<T, T>) collection).clear(); 59 return null; 60 } 61 62 public String toString() { 63 return "SortedMap"; 64 } 65 }